I’ve got a select box with some options. I want to allow a user to choose an option and then be taken to a URL stored in that option’s value attribute. However, my script keeps opening the new window on page load, not on change. Why?! Help!
function selectBoxNav() {
"use strict";
var mySelectBox = document.getElementById('mySelectBox');
var myOption = mySelectBox.options[mySelectBox.selectedIndex];
var myURL = myOption.value;
function newWindow() {
window.open(myURL);
}
mySelectBox.addEventListener('change', newWindow(), false);
}
window.addEventListener('DOMContentLoaded', selectBoxNav(), false);
You need to pass the function to
addEventListener(), but instead you’re calling it and passing its return value.newWindow()calls the function. To pass it you should remove the parentheses:mySelectBox.addEventListener('change', newWindow, false);