• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Toggle four photos with a click

anuraa

Legendary Coder
Hi friends:

I was successful with toggling two photos. I am trying to expand it to four photos without any success. I am grateful for your helps.

HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Switch Images</title>
    <style>
      *{margin: 0; padding: 0; box-sizing: border-box; }
      p{font-size: 24px;}
    </style>
</head>
<body>
    <p>between two images</p>
    <div>
        <img src="one.jpg" id="images1">
    </div>
    <p>between four images</p>
    <div>
        <img src="three.jpg" id="images2">
    </div>
<script>
    const img = document.getElementById('images1');
    let toggle = true;
    img.addEventListener('click',function(){
       toggle = !toggle;
       if(toggle){
          img.src = 'one.jpg';
          }else{
          img.src = 'two.jpg';
        }
    });     
</script>
<script>
    const img2 = document.getElementById('images2');
    let toggle2a = true;
    let toggle2b = true;
    img2.addEventListener('click',function(){
        toggle2a = !toggle2a;
        toggle2b = !toggle2b;
        if(toggle2a){
          img2.src = 'one.jpg';
        }else
            {if(toggle2b){
                img2.src= 'two.jpg'
            }else{
                img2.src='three.jpg'
            }
            img2.src = 'four.jpg';
        }
    });     
</script>
</body>
</html>
 

Attachments

  • four.jpg
    four.jpg
    19 KB · Views: 4
  • three.jpg
    three.jpg
    23.5 KB · Views: 4
  • two.jpg
    two.jpg
    20.2 KB · Views: 4
  • one.jpg
    one.jpg
    23.6 KB · Views: 4
Solution
Hello friends:

I found the following code to be working. However, there are two issues that I would like to get it clear.
1. to overcome the first click on first div, going to the third element, I coded the fist images array as follows.
var images = ['four.jpg', 'one.jpg', 'two.jpg', 'three.jpg'],
// * images = ['two.jpg', 'three.jpg', 'four.jpg', 'one.jpg'],
2. Sometimes, when I switched between two divs for images, I have to click twice on the image.

You guys, may be able to help me fine tune the code with my above observations. No clues, but something like resetting, loading the images to arrays .

HTML:
<html>
<head>
</head>
    <body>
        <div>
            <p>With four images</p>
              <img...
Hi friends:

I was successful with toggling two photos. I am trying to expand it to four photos without any success. I am grateful for your helps.

HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Switch Images</title>
    <style>
      *{margin: 0; padding: 0; box-sizing: border-box; }
      p{font-size: 24px;}
    </style>
</head>
<body>
    <p>between two images</p>
    <div>
        <img src="one.jpg" id="images1">
    </div>
    <p>between four images</p>
    <div>
        <img src="three.jpg" id="images2">
    </div>
<script>
    const img = document.getElementById('images1');
    let toggle = true;
    img.addEventListener('click',function(){
       toggle = !toggle;
       if(toggle){
          img.src = 'one.jpg';
          }else{
          img.src = 'two.jpg';
        }
    });   
</script>
<script>
    const img2 = document.getElementById('images2');
    let toggle2a = true;
    let toggle2b = true;
    img2.addEventListener('click',function(){
        toggle2a = !toggle2a;
        toggle2b = !toggle2b;
        if(toggle2a){
          img2.src = 'one.jpg';
        }else
            {if(toggle2b){
                img2.src= 'two.jpg'
            }else{
                img2.src='three.jpg'
            }
            img2.src = 'four.jpg';
        }
    });   
</script>
</body>
</html>
Hey there :)
So I tested your code, and works great! However, you may have put in just a bit more work than was required :). So I have a solution for you that will work in either situation: First and foremost: you are going to want to add an id to the containers of the images, in my case, I gave them '2-img' and '4-img' respectively. This will come in handy later. NOTE: might want to comment out your earlier code to give this a test :)

JavaScript:
    //add all links in an array, or if you don't know the naming convention, read the names onto the array
    const imageLinks = ['one.jpg','two.jpg','three.jpg','four.jpg'];
   
    //grab all the images from the DOM
    var images = document.querySelectorAll('img');
   
    //loop through all the images
    images.forEach((image) =>{

        //add click event listener to each
        image.addEventListener('click', (event) => {
            //grab the container of the image that was clicked
            var container = event.target.closest('div');

            //grab the index of the image that was clicked, from the array of links
            var currentIndex = imageLinks.indexOf(event.target.getAttribute('src'));
           
            //increase the index by 1
            currentIndex++;

            //set a threshold for the index, in order to avoid getting an out of bounds exception
            //here, if the id of the current container matches '2-img', then the threshold is set to 1, otherwise it is set to three.
            //Remember, arrays are 0-based index wise.
            var indexThreshold = (container.id == '2-img') ? 1 : 3;

            //check if index is greater than threshold. If so, reset index to 0, otherwise keep as is
            currentIndex = (currentIndex > indexThreshold) ? 0 : currentIndex;

            //set the source attribute/property of the image to the next image in line
            event.target.src = imageLinks[currentIndex];
           
        });
    });
 
Thank you very much. I learnt many things with your comments to explain. I am trying to expand your brilliant concept. That is to toggle 3 different images in a different div to that of 4 images inside the first div. I am struggling there. Hope, you could help me. I have attached here the code with your suggestion and my adding of another div below for 3 other images.
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Switch Images</title>
    <style>
      *{margin: 0; padding: 0; box-sizing: border-box; }
      p{font-size: 24px;}
    </style>
</head>
<body>
   
    <p>between four images</p>
    <div>
        <img src="one.jpg" id="4-img">
    </div>
    <p>between three images with another 3 different images in a different place</p>
    <div>
        <img src="nangi.jpg" id="3-img">
    </div>
   
<script>
   
     //add all links in an array, or if you don't know the naming convention, read the names onto the array
     const imageLinks = ['one.jpg','two.jpg','three.jpg','four.jpg'];
 
   //grab all the images from the DOM
   var images = document.querySelectorAll('img');
 
   //loop through all the images
   images.forEach((image) =>{

       //add click event listener to each
       image.addEventListener('click', (event) => {
           //grab the container of the image that was clicked
           var container = event.target.closest('div');

           //grab the index of the image that was clicked, from the array of links
           var currentIndex = imageLinks.indexOf(event.target.getAttribute('src'));
         
           //increase the index by 1
           currentIndex++;

           //set a threshold for the index, in order to avoid getting an out of bounds exception
           //here, if the id of the current container matches '2-img', then the threshold is set to 1, otherwise it is set to three.
           //Remember, arrays are 0-based index wise.
           var indexThreshold = (container.id == '4-img') ? 1 : 3;

           //check if index is greater than threshold. If so, reset index to 0, otherwise keep as is
           currentIndex = (currentIndex > indexThreshold) ? 0 : currentIndex;

           //set the source attribute/property of the image to the next image in line
           event.target.src = imageLinks[currentIndex];
         
       });
   });    
</script>
</body>
</html>
 
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Switch Images</title>
    <style>
      *{margin: 0; padding: 0; box-sizing: border-box;}
      p{font-size: 24px;}
      .wrap img{cursor: pointer;}
    </style>
    <script>
    const imgObj = {
        'Between two images'  : ['one.jpg', 'two.jpg'], /* pictures given by topic starter */
        'Between four images' : ['one.jpg', 'two.jpg', 'three.jpg', 'four.jpg'], /* pictures given by topic starter */
        'Between other pictures' : [
                                    'https://codeforum.org/data/avatars/m/6/6408.jpg',
                                    'https://codeforum.org/data/avatars/m/0/139.jpg',
                                    'https://codeforum.org/data/avatars/m/6/6434.jpg',
                                    'https://codeforum.org/data/avatars/m/6/6592.jpg'
                                    ] /* some avatars from the forum */
    }
    
    onload = () => {
        document.body.insertAdjacentHTML( 'afterbegin', Object.entries( imgObj ).map( x => `<div class="wrap"><p>${x[0]}</p><div><img data-index="0" src="${x[1][0]}"></div></div>` ).join('') );
        
        document.querySelectorAll('.wrap img').forEach( img => {
            img.addEventListener( 'click', function(e){
            const trg = e.target,
                  ar = imgObj[trg.closest('.wrap').querySelector('p').textContent],
                  next = +trg.dataset.index + 1;
                  
                  ar[next]
                    ? [trg.src = ar[next], trg.dataset.index = next]
                        : [trg.src = ar[0], trg.dataset.index = '0'];
                  
            });
        });
    }
    </script>
</head>
<body></body>
</html>
 
Thank you very much. It was working fine. Lots of new concepts. I was looking for two (now three) javascripts tagged/referenced with id of the dev. That way I can comfortably decorate my DOM. Thanks again
 
Hello friends:

I found the following code to be working. However, there are two issues that I would like to get it clear.
1. to overcome the first click on first div, going to the third element, I coded the fist images array as follows.
var images = ['four.jpg', 'one.jpg', 'two.jpg', 'three.jpg'],
// * images = ['two.jpg', 'three.jpg', 'four.jpg', 'one.jpg'],
2. Sometimes, when I switched between two divs for images, I have to click twice on the image.

You guys, may be able to help me fine tune the code with my above observations. No clues, but something like resetting, loading the images to arrays .

HTML:
<html>
<head>
</head>
    <body>
        <div>
            <p>With four images</p>
              <img id="myTouch1" src="one.jpg" />
        </div>
        <div>
            <p>With two images</p>
              <img id="myTouch2" src="nangi.jpg" />
        </div>

        <script type="text/javascript">
            var images = ['four.jpg', 'one.jpg', 'two.jpg', 'three.jpg'],
            // * images = ['two.jpg', 'three.jpg', 'four.jpg', 'one.jpg'],
                i = 1;
            for (var j=images.length; j--;) {
                var img = new Image();
                img.src = images[j];
            }
            document.getElementById('myTouch1').addEventListener('click', function() {
                this.src = images[i >= images.length - 1 ? i = 0 : ++i];
            }, false);
        </script>
        <script type="text/javascript">
            var images2 = ['nangif.jpg', 'nangi.jpg'],
                i = 1;
            for (var j=images2.length; j--;) {
                var img = new Image();
                img.src = images[j];
            }
            document.getElementById('myTouch2').addEventListener('click', function() {
                this.src = images2[i >= images2.length - 1 ? i = 0 : ++i];
            }, false);
        </script>
    </body>
</html>
 

Attachments

  • nangi.jpg
    nangi.jpg
    65.9 KB · Views: 1
  • nangif.jpg
    nangif.jpg
    149.9 KB · Views: 1
Solution
Thank you very much. I learnt many things with your comments to explain. I am trying to expand your brilliant concept. That is to toggle 3 different images in a different div to that of 4 images inside the first div. I am struggling there. Hope, you could help me. I have attached here the code with your suggestion and my adding of another div below for 3 other images.
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Switch Images</title>
    <style>
      *{margin: 0; padding: 0; box-sizing: border-box; }
      p{font-size: 24px;}
    </style>
</head>
<body>
 
    <p>between four images</p>
    <div>
        <img src="one.jpg" id="4-img">
    </div>
    <p>between three images with another 3 different images in a different place</p>
    <div>
        <img src="nangi.jpg" id="3-img">
    </div>
 
<script>
 
     //add all links in an array, or if you don't know the naming convention, read the names onto the array
     const imageLinks = ['one.jpg','two.jpg','three.jpg','four.jpg'];
 
   //grab all the images from the DOM
   var images = document.querySelectorAll('img');
 
   //loop through all the images
   images.forEach((image) =>{

       //add click event listener to each
       image.addEventListener('click', (event) => {
           //grab the container of the image that was clicked
           var container = event.target.closest('div');

           //grab the index of the image that was clicked, from the array of links
           var currentIndex = imageLinks.indexOf(event.target.getAttribute('src'));
      
           //increase the index by 1
           currentIndex++;

           //set a threshold for the index, in order to avoid getting an out of bounds exception
           //here, if the id of the current container matches '2-img', then the threshold is set to 1, otherwise it is set to three.
           //Remember, arrays are 0-based index wise.
           var indexThreshold = (container.id == '2-img') ? 1 : 3;

           //check if index is greater than threshold. If so, reset index to 0, otherwise keep as is
           currentIndex = (currentIndex > indexThreshold) ? 0 : currentIndex;

           //set the source attribute/property of the image to the next image in line
           event.target.src = imageLinks[currentIndex];
      
       });
   }); 
</script>
</body>
</html>
Hey there! :)
Glad to see you are learning new concepts and ways to code. So for your what you are looking for now, it wouldn't be too bad of a change. All that would be needed to change would be this line
JavaScript:
//set a threshold for the index, in order to avoid getting an out of bounds exception
//here, if the id of the current container matches '2-img', then the threshold is set to 1, otherwise it is set to three.
//Remember, arrays are 0-based index wise.
var indexThreshold = (container.id == '2-img') ? 1 : 3;

So, in my solution, I created one if statement. For your change, you can go a couple different ways:
1) What I call "cascading if-else"
JavaScript:
if( container.id == '2-img' ) {
    //set indexThreshold to 1
} else if ( container.id == '3-img' ) {
    //set indexThreshold to 2
} else if ( container.id == '4-img' ) {
    //set indexThreshold to 3
}

2) switch-case statement
JavaScript:
switch ( containerID ) {
    case '2-img':
        //set indexThreshold to 1
        break;
    case '3-img':
        //set indexThreshold to 2
        break;
    case '4-img':
        //set indexThreshold to 3
        break;
}

If it makes it easier, you can set indexThreshold to (length of Array - 1)
var indexThreshold = images.length - 1

This would honestly get rid of the need for checking for the id

In any event, you would still need to tie an id to the div
 
Last edited:
Hey there! :)
Glad to see you are learning new concepts and ways to code. So for your what you are looking for now, it wouldn't be too bad of a change. All that would be needed to change would be this line
JavaScript:
//set a threshold for the index, in order to avoid getting an out of bounds exception
//here, if the id of the current container matches '2-img', then the threshold is set to 1, otherwise it is set to three.
//Remember, arrays are 0-based index wise.
var indexThreshold = (container.id == '2-img') ? 1 : 3;

So, in my solution, I created one if statement. For your change, you can go a couple different ways:
1) What I call "cascading if-else"
JavaScript:
if( container.id == '2-img' ) {
    //set indexThreshold to 1
} else if ( container.id == '3-img' ) {
    //set indexThreshold to 2
} else if ( container.id == '4-img' ) {
    //set indexThreshold to 3
}

2) switch-case statement
JavaScript:
switch ( containerID ) {
    case '2-img':
        //set indexThreshold to 1
        break;
    case '3-img':
        //set indexThreshold to 2
        break;
    case '4-img':
        //set indexThreshold to 3
        break;
}

If it makes it easier, you can set indexThreshold to (length of Array - 1)
var indexThreshold = images.length - 1

This would honestly get rid of the need for checking for the id

In any event, you would still need to tie an id to the div
Thanks. I like to learn your style of solution as well. I was not clear before telling this. In two div tags, I have got entirely two different set of images. I would love to see the complete set of codes, if you could please. Thanks again
 
Thanks. I like to learn your style of solution as well. I was not clear before telling this. In two div tags, I have got entirely two different set of images. I would love to see the complete set of codes, if you could please. Thanks again
You can still use the implementation, just create another array to hold the file names of the second set of images. In the event handler, again, check for the container that was clicked, and depending on what you need on each container, assign the right array. Something like this:

JavaScript:
const  set1 = ['one.jpg', 'two.jpg', 'three.jpg', 'four.jpg'];
const set2 = ['five.jpg', 'six.jpg', 'seven.jpg', 'eight.jpg'];


            //check the container id and grab the index of the image that was clicked, from correct array of links
            var currentIndex = ( container.id == '2-img' ) ? set.indexOf(event.target.getAttribute('src')) : set2.indexOf(event.target.getAttribute('src'));

Make sure you put that last part in the right spot :)
As a side note: please include all parts of what you need in the question :) makes things a lot easier for everyone, and less having to adjust to specification changes
 

New Threads

Latest posts

Buy us a coffee!

300x250
Top Bottom