Apply now

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

Modern Javascript in the Browser
Share article
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.
  };
});


Conclusion


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!
Want to know more about Le Wagon's 9-week bootcamp?
Download Syllabus
Keep reading
Graduate stories

My Coding Bootcamp journey in Barcelona

I started to be interested in coding a few of years ago while travelling. After meeting many inspiring developers in hostels, who were working remotely while travelling and making good money. At the time I never really considered myself technically minded enough or able to sit at a computer for long enough to be able to make this a career. I decided to give it a go, and took some online courses. I loved it. Before then I didn't realise that coding is a an excellent job for creative people.

News

In 2020, Le Wagon turns 6 years old: let's celebrate

How many lives can be changed in 6 years? Le Wagon is turning 6 years old this month and we're celebrating with our community of 6,600+ alumni! Back in 2014, we bootstrapped a company aiming to transform education with one mission: helping people and organisations succeed by teaching them the skills of tomorrow.

Graduate stories

The Microbiologist Who Became A Developer

Jessica is a problem solver and an entrepreneur by nature. She graduated with two bachelor degrees, one in medical biology and another in environmental science. Upon graduation, she worked as a microbiologist then decided to transition into programming, a field where she could express her creativity.

Interested in joining the #1 ranked coding bootcamp?

We are in 38 cities worldwide.