Choose a city

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
Learn to code

Tech is also a woman's world

Did you know that women are under-represented in technical roles at under 20% industry wide? It's as low as 2% at the VC level! At Le Wagon we're proud to be pushing for more gender equality on all our batches worldwide. We took a look at our London data and thought we'd share some awesome stats on our power wagon-women!

Graduate stories

From Hotel Manager to Developer/ Digital Marketeer in US Startup

As is so common when you’re in your early twenties, Guilherme “Gui” Andrade went through quite a bit of trial and error trying to find what made him ‘tick.' After studying architecture, then civil engineering, Gui decided to stick it out with hospitality management and went to Switzerland to complete his university degree.

Graduate stories

Why a coding bootcamp (Le Wagon Barcelona) was the best choice for me!

Le Wagon has been an incredible experience in an uncountable amount of ways. If you’re considering doing a coding boot camp, choose Le Wagon. (and no I wasn’t paid to say this 😂)

Interested in joining the #1 ranked coding bootcamp?

We are in 39 cities worldwide.