Abdulaziz B.
Abdulaziz B.

Reputation: 13

addEventListener isn't working with multi elements by getElementsByClassName

I'm trying to use addEventListener click with two buttons having the same class but it isn't working!

This is the :

<div class="share-block">
  <a href="#" class="btn-rounded share-btn"><i class="fa fa-share-alt fa-2x"></i></a>
  <div class="social-block">
    <a href="http://facebook.com/share" class="btn-rounded btn-sm social-btn btn-fb"><i class="fa fa-facebook"></i></a>
    <a href="http://twitter.com/share" class="btn-rounded btn-sm social-btn btn-tw"><i class="fa fa-twitter"></i></a>
  </div>
</div>

And here's the code:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', function(event) {
    window.open(socialBtns[i].href, "Share", "width=600,height=400");
    event.preventDefault();
  });
}

Upvotes: 1

Views: 81

Answers (1)

InstilledBee
InstilledBee

Reputation: 131

Use this.href on your event handlers instead of referencing the socialBtns variable in the for-loop:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
    socialBtns[i].addEventListener('click', function(event) {
       window.open(this.href, "Share", "width=600,height=400");
       event.preventDefault();
    });
}

You could also improve on the existing code by creating the event handler outside of the for-loop:

var socialBtns = document.getElementsByClassName('social-btn');

for (var i = 0; i < socialBtns.length; i++) {
  socialBtns[i].addEventListener('click', openSocialLink);
}

function openSocialLink(event) {
  window.open(this.href, "Share", "width=600,height=400");
  event.preventDefault();
}

JSFiddle sample

Upvotes: 1

Related Questions