简体   繁体   中英

Javascript image source change addEventListener “click” event

Trying to use JavaScript to change the image source from images/small/ to images/medium/

I have tried the following code but for some reason the click event is not being picked up, thanks for any help with this.

Javascript

var thumbs = document.getElementById("thumbnails");

thumbs.addEventListener("click", function (i) {


    if (i.target.nodeName.toLowerCase() == "img") {
        // get image filename of clicked thumbnail
        var clickedImageSource = i.target.src;

        // replace the folder name of the image 
        var newSrc = clickedImageSource.replace("small","medium");


    }

});

HTML

<div id="thumbnails">
        <img src="images/small/Home.jpg" title="Home" />
        <img src="images/small/Office.jpg" title="Office" />
        <img src="images/small/Park.jpg" title="Park" />
        <img src="images/small/Hills.jpg" title="Hills" />
        <img src="images/small/HaveEyes.jpg" title="HaveEyes" />
    </div>

You can't attach event listeners before the DOM element is available.

 <script> // executed before dom is ready. var thumbs = document.getElementById("thumbnails"); thumbs.addEventListener("click", function(i) { console.log('clicked'); }); </script> <div id="thumbnails"> <img src="images/small/Home.jpg" title="Home" /> <img src="images/small/Office.jpg" title="Office" /> <img src="images/small/Park.jpg" title="Park" /> <img src="images/small/Hills.jpg" title="Hills" /> <img src="images/small/HaveEyes.jpg" title="HaveEyes" /> </div> <script> // executed after dom is ready. var thumbs = document.getElementById("thumbnails"); thumbs.addEventListener("click", function(i) { console.log('clicked'); }); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM