tsu90280
tsu90280

Reputation: 437

Images keep opening in browser instead of running click event

I have written a small snippet for a div section which is shown below.

window.onload = function() {
  var links = gallery.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('onclick', function(e) {
      // Hide results
      document.getElementById('placeholder').style.display = 'none';

      // Show loader
      document.getElementById('loading').style.display = 'block';

      // setTimeout(calculateResults, 2000);

      e.preventDefault();
    });

  }
}
<div id="content">
  <h3>Select Images Below</h3>
  <ul id="imagegallery">
    <li>
      <a href="./img/1.jpg" title="The crowd goes wild">
        <img src="./img/large-1.jpg" alt="the band in concert" />
      </a>
    </li>
    <li>
      <a href="./img/2.jpg" title="An atmospheric moment">
        <img id='image' src="./img/large-2.jpg" alt="the bassist" />
      </a>
    </li>
    <li>
      <a href="./img/3.jpg" title="Rocking out">
        <img id='image' src="./img/large-3.jpg" alt="the guitarist" />
      </a>
    </li>
    <li>
      <a href="./img/4.jpg" title="Encore! Encore!">
        <img id='image' src="./img/large-4.jpg" alt="the audience" />
      </a>
    </li>
  </ul>
  <div>
    <img id='placeholder' , src="./img/resources/neutral_1.jpg" , alt="Image gooes here" , style="margin-bottom: 50px;padding: 10px;">
  </div>
  <div id="loading">
    <img src="img/loading.gif" alt="">
  </div>
</div>

My main goal is to click the thumbnail image and larger version of this image displays in div below, after showing a loader and added delay, which i want to do dynamically using JS. But the problem is whenever i click on image it opens up thumbnail in browser in same window. What am i doing wrong over here.

Upvotes: 1

Views: 97

Answers (1)

MGuilmet
MGuilmet

Reputation: 201

The root problem you are running into is you are using addEventListener('onclick')

this should be: addEventListener('click')

"onclick" is the attribute, "click" is the event

Also, you reference gallery in the onload, unless this is set somewhere higher up, this should just be document.

After that's worked out, you'll need to set the source of your placeholder. You can do something like this:

links[i].addEventListener('click', function(e) {
   var placeholder = document.getElementById('placeholder');
   placeholder.src = e.currentTarget.getElementsByTagName("img")[0].src;
   e.preventDefault();
});

Hope this gets you where you need to be.

Upvotes: 1

Related Questions