I have a calendar of the month and I need to open a new window that let's enter different info on the onclick
event. So I have a for loop in which I set the onclick()
event to many divs. The title attribute holds the day of the month that was clicked.
This is my code, but no matter what day of the month I click, it's always the same one:
window.onload = function () {
'use strict';
var i = 0, newAppt, infoGet;
newAppt = document.getElementsByTagName('div');
for (i = 0; i < newAppt.length; i++) {
if (newAppt[i].getAttribute('title') !== '') {
infoGet = newAppt[i].getAttribute('title');
newAppt[i].addEventListener('click', newApptWin(infoGet), false);
}
}
};
function newApptWin(infoGet) {
'use strict';
window.open(infoGet,'test','toolbar=0');
}
Any help?
Your code runs the function newApptWin(infoGet) immediate as your page loads, and it never changes. You're supposed to pass a function to the eventListener, not the result of the function (which you have done here). You can fix it like so:
newAppt[i].addEventListener('click', function() {newApptWin(infoGet);}, false);
Edit (update this is wrong):
Declare infoGet within the for loop. your entire script:
window.onload = function () {
'use strict';
var i = 0, newAppt;
newAppt = document.getElementsByTagName('div');
for (i = 0; i < newAppt.length; i++) {
if (newAppt[i].getAttribute('title') !== '') {
var infoGet = newAppt[i].getAttribute('title');
newAppt[i].addEventListener('click', function() {newApptWin(infoGet);}, false);
}
}
};
function newApptWin(infoGet) {
'use strict';
window.open(infoGet,'test','toolbar=0');
}
Or you can skip infoGet completely and avoid a potential memory leak:
newAppt[i].addEventListener('click', function() {newApptWin(newAppt[i].getAttribute('title'));}, false);
Edit 2:
window.onload = function () {
'use strict';
var i = 0, newAppt;
newAppt = document.getElementsByTagName('div');
for (i = 0; i < newAppt.length; i++) {
if (newAppt[i].getAttribute('title') !== '') {
var infoGet = newAppt[i].getAttribute('title');
newAppt[i].addEventListener('click', newApptWin, false);
}
}
};
function newApptWin() {
'use strict';
window.open(this.getAttribute('title'),'test','toolbar=0');
}