Practicing with Mozilla exercises

Practicing with Mozilla exercises
0.0 0

#1

I got stuck on freecodecamp’s API exercise so I decided to practice JS some more with Mozilla’s web development tutorial and then come back to freecodecamp. Hopefully it is OK to ask questions here about another website’s tutorial.

I am trying to understand the JS code behind this page: https://mdn.github.io/learning-area/javascript/building-blocks/gallery/

You should be able to view the JS code by viewing Source code then clicking on the main.js link to open the JS file.

The idea of this webpage is to click on the thumbnail so that pic becomes the larger image. And the part of the JS code that deals with that is this:

/* Looping through images */

for(var i = 1; i <= 5; i++) {
  var newImage = document.createElement('img');
  newImage.setAttribute('src', 'images/pic' + i + '.jpg');
  thumbBar.appendChild(newImage);
  newImage.onclick = function(e) {
    var imgSrc = e.target.getAttribute('src');
    displayImage(imgSrc);
  }
}

I am really confused about what this code is doing and would appreciate a layman’s explanation.

Many thanks!


#2

When the page first loads, none of those images are present. This loop does a few things:

Sets up a loop to run from 1 to 5:

for(var i = 1; i <= 5; i++)

For each iteration, it creates an image element:

var newImage = document.createElement('img');

It sets the source of that element to the path images/pic + i + .jpg:

newImage.setAttribute('src', 'images/pic' + i + '.jpg');

It jams this new image onto the page in a spot called the “thumBar”:

thumbBar.appendChild(newImage);

Finally, it sets the onclick event handler for the new image:

newImage.onclick = function(e) {
    var imgSrc = e.target.getAttribute('src');
    displayImage(imgSrc);
  }

This image handler will set whichever image you’ve clicked on to appear in the large, centered area.


#3

Thanks @PortableStick! That clarified quite a bit.

I have some other questions:

1 - Why is the onclick event handler IN the loop? The loop runs as soon as the page loads. But I need the onclick event to run when I click on an image?

2 - What does (e) mean…? (Maybe my lack of understanding here is contributing to lack of understanding in Qn 1…?)

Also, the onclick event handler invokes a function called displayImage but that function is not defined until later on in the code…is it OK to invoke a function in the code before that function is defined?

Thanks again!


#4

The click handler isn’t being run in the loop, just attached.

Every event gets passed an event object. It’s super useful to know about, so I suggest you take a look at the properties and methods in that link. e.preventDefault() is particularly useful. See if you can find out what e.target refers to.

It sure is. Some people even prefer that style.


#5

Thanks @PortableStick super helpful !