Rgrunwald
Rgrunwald

Reputation: 41

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>

Upvotes: 4

Views: 12741

Answers (1)

jens
jens

Reputation: 2145

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>

Upvotes: 2

Related Questions