0

Take a look at the following JavaScript for me that opens a pop up window, please:

function openPopup(e) {
    e.preventDefault();
    window.open(this.href, "popupWindow", "width=600,height=600,scrollbars=yes");
}
var el = document.querySelector(".bbc-popup");
el.addEventListener("click", openPopup);

Here is a JSFiddle of it in action:

http://jsfiddle.net/dvadcgps/1/

However, when I include it on my page, the code doesn't work, and the link opens in the current tab. The only external JavaScript resources I rely on are jQuery (1.11.3) and Bootstrap 3, and those are both included within the above fiddle, to no effect.

What other reasons could there be for this code to not work?

Here is the full HTML code of the page, with all external resources included, for you to see how it stops working... the links that should open popups are behind the View Chairs' Builds button:

http://jsfiddle.net/e60y004n/1/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
mpdc
  • 3,550
  • 5
  • 25
  • 48
  • Your code works fine for me in that I see a new 600x600 popup window (Chrome 46 on W8.1). I would imagine the preferences for whether a new window is allowed to be opened or is opened in a new tab is down to the user settings in the browser. – Rory McCrossan Nov 12 '15 at 17:19
  • 2
    You're only adding the event listener to the first `.chair-popup` element. Check out [this question](http://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class). – Brian Ray Nov 12 '15 at 17:25
  • Fantastic, Brian. This seems to work now: http://jsfiddle.net/e60y004n/3/ Pop it in an answer and I'll be happy to accept. – mpdc Nov 12 '15 at 17:30

1 Answers1

0

Working off Brian Ray's comment, I had to ensure the Event Listener was added to every element, as my current code was only adding it to the first.

Firstly, I add all the elements I want to be targeted to an array.

var chairPopup = document.getElementsByClassName("chair-popup");

I then loop through every element in that array, adding the Event Listener to each:

for (var i = 0; i < chairPopup.length; i++) {
    chairPopup[i].addEventListener("click", openPopup);
}

The full code, with the function(), reads as follows:

var chairPopup = document.getElementsByClassName("chair-popup");

function openPopup(e) {
    e.preventDefault();
    window.open(this.href, "popupWindow", "width=300,height=1000,scrollbars=yes");
}
for (var i = 0; i < chairPopup.length; i++) {
    chairPopup[i].addEventListener("click", openPopup);
}

In an answer that has since been deleted by it's author, they mentioned a need to change popupWindow to _blank within the window.open() function. I can confirm that this is needed, otherwise each link opens up in the same popup window.

window.open(this.href, "_blank", "width=300,height=1000,scrollbars=yes");
Community
  • 1
  • 1
mpdc
  • 3,550
  • 5
  • 25
  • 48