Jue Debutat
Jue Debutat

Reputation: 367

Avoid popup block with attached event listener

I've got about 10 buttons of class "serviceButton" that also contain a custom attribute called "about". They look like this:

<li>
    <button type="button" class="serviceButton serviceButton-red" about="http://blabla">Identity Service</button>
</li>
<li>
    <button type="button" class="serviceButton serviceButton-red" about="http://secondLink,etc">VPN</button>
</li>

I've also got some javascript on the page which loops through all buttons of that class and attaches a listener to them that is going to get the value of the about attribute and open up a new window by that. (I am trying to make the site work both on mobile/touch events and desktop/click events).

var classname = document.getElementsByClassName("serviceButton");

var open = function() {
    var attribute = this.getAttribute("about");
    alert("start");
    var win = window.open(attribute, '_blank');
    win.focus();
    alert("stop");
};

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('touchstart', open, false);
}

The first alert gets called successfully, whereas the second one does not; neither does a new tab open. How can I solve this issue by using just js?(No jQuery etc...)

Upvotes: 0

Views: 797

Answers (1)

lkostka
lkostka

Reputation: 751

Avoid attaching multiple eventListeners like this, and add it the parent instead.

Here's an exemple, with onclick event, you can adapt it to your problem and it should do the trick.

http://jsfiddle.net/3r7rq8vc/

<ul>
  <li about="http://www.google.com">Google</li>
  <li about="http://www.devrant.io">Devrant</li>
</ul>


<script>
var listParent,
    listenerId,
    openLink;

openLink = function(e) {
  var targetLink = e.target.getAttribute('about');
  // Trying to open
  window.open(targetLink, '_blank')
}


// Prefer adding event listener to the parent
listParent = document.querySelector('ul');
listenerId = listParent.addEventListener('click', openLink);
</script>

Upvotes: 1

Related Questions