Go to lewagon.com

Modern Javascript in the Browser

When it comes to working with JavaScript in the browser, there is only 3 concepts you need to master. DOM selection, Event Handling and AJAX
When it comes to working with JavaScript in the browser, there's three concepts you need to master. First, you should know how to select and query elements in the DOM, and store them in variables. Then, you should be able to add event listeners to some elements to react to specific events. At last, you should know how to perform AJAX requests to fetch some information after the initial page load.

1 - DOM Selection

Suppose you have the following HTML:

<ul id="cities">     <li class="europe">Paris</li>     <li class="europe">London</li>   <li class="europe">Berlin</li>   <li class="asia">Shanghai</li>   <li class="america">Montreal</li> </ul>

The easiest way to select a DOM element is using its id attribute:

const list = document.getElementById("cities");

There is another way, using a CSS selector:
const list = document.querySelector("#cities");
Those two methods will always return a single element. Guaranteed. If you want to select all the lis with the europe class inside your list, you will use a fancier CSS query selector:

const europeanCities = document.querySelectorAll("#cities .europe"); europeanCities.forEach((city) => {     city.classList.add('highlight'); });

In the code above, notice that querySelectorAll always returns a NodeList (which may contain only one element). You can call the forEach method on this list. We also used an ES6 arrow function which has a wide support. You should consider Babel to support the remaining ones or revert to a classic anonymous function definition.

To walk the DOM from a given element, have a look at parentElement, children and nextElementSibling. It's a big family tree!

2 - Binding and handling Events

The browser is a Graphical User Interface (GUI). It means that a user will interact with it, and you can't predict what her action will be. Will she click on button A first? Or scroll a bit to click on this link? Or hover that image?

When using a website, the browser emits tons of events. Every time you scroll one pixel down with your trackpad or mouse, a scroll event is fired. You can test it yourself! Open your Browser Console (using the Web Inspector) and type this JavaScript line (then press Enter):

document.addEventListener('scroll', () => console.log(document.body.scrollTop));

And now, scroll! Crazy isn't it? Each event logged represents one pixel scrolled down or up since the page was loaded

Suppose you have the following HTML:

<button id="openModal"></button>

You can bind a callback to the click event on that button with the following JavaScript code:

const button = document.getElementById('openModal'); button.addEventListener("click", (event) => {     console.log(event.target);  // `event.target` is the element on which the user clicked   alert("You clicked me!");  // TODO: implement a modal opening logic instead of this alert  });

You can read more about addEventListener on the MDN web docs

3 - AJAX

AJAX is the cornerstone of the modern Web. Thanks to this technology, a web page can be refreshed in the background with new information. You can think of Gmail's new emails showing up in the Inbox, Facebook notifying you that new content is available in your timeline, etc.
With modern web browsers, we can use fetch. Here is an example of calling a JSON API with a GET request:

fetch(url)     .then((response) => response.json())     .then((data) => {         console.log(data); // data will be the JSON fetched from the API    });

Sometimes, we need to POST information to an API:

// Some info to POST  const payload = { name: 'Name', email: 'Email' };  fetch(url, {     method: "POST",    headers: {    "Content-Type": "application/json"  },     body: JSON.stringify(payload)})    .then(response => response.json())  .then((data) => {         console.log(data); // JSON from the API response.   }; });


You can now combine these three techniques to create dynamic web pages! You will select elements thanks to one of the three methods (getElementById, querySelector or the one returning an NodeList: querySelectorAll). With an element at hand, you can addEventListener on a given event type (click, focus, blur, submit, etc.). The callback passed to this listener could contain an AJAX call using fetch.
Happy JavaScripting!
Our users have also consulted:
Pour développe mes compétences
Formation développeur web
Formation data scientist
Formation data analyst
Les internautes ont également consulté :

Suscribe to our newsletter

Receive a monthly newsletter with personalized tech tips.