Jue Debutat Jue Debutat - 1 year ago 78
Javascript Question

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:

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

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");
var win = window.open(attribute, '_blank');

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...)

Answer Source

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.


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

var listParent,

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download