Vanilla javascript photo gallery?

It is a image gallery code on clicking the imgs(8 images) current image(main image) get changed .But how the forEach knows that we are clicking the respective image.If its jquery we use this keyword ?

<div class="container">
       <div class="main-img">

        <img src="img/img1.jpeg" id="current">

       <div class="imgs">

        <img src="img/img1.jpeg">
        <img src="img/img2.jpeg">
        <img src="img/img3.jpeg">
        <img src="img/img4.jpeg">
        <img src="img/img5.jpeg">
        <img src="img/img6.jpg">
        <img src="img/img7.jpg">

        <img src="img/img8.jpeg">


var current = document.querySelector('#current');

var imgs = document.querySelectorAll('.imgs img');



The .forEach() method iterates over all elements in the NodeList, and the iterator function takes the current element as its first argument (which is your aptly named element parameter). This is part of the DOM specification, there is no jQuery involved here.

It should be noted though that some browsers fail to implement the full DOM specs; to make it work in IE as well, you’ll have to “borrow” the .forEach() method from the Array prototype first:

NodeList.prototype.forEach = Array.prototype.forEach

(PS: or not to override existing native implementations:)

NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach
1 Like

But how it takes the clicked element as argument.Because there are 8 elements in imgs?

// current is a single element
var current = document.querySelector('#current')
// imgs is a node list containing all img elements
// that match your query selector ('.imgs img')
var imgs = document.querySelectorAll('.imgs img')

imgs.forEach(function (element) {
  // To each element in the node list, you add a 
  // 'click' event listener
  element.addEventListener('click', function (e) {
    // You assign the event target's .src to
    // the current .src; and the event target
    // is the element that got actually clicked.
    // In your case it will always be so that
    // === element
    current.src =
1 Like

thanks got it…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.