I have a Visualforce error that's driving me crazy. My Javascript file ui.js (see blow) is just defining an onclick event on a DOM element. Here is my javascript :
(function (window, document) {
var layout = document.getElementById('layout');
var menu = document.getElementById('menu');
var menuLink = document.getElementById('menuLink');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
function clickOnMenu (e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
};
menuLink.onclick = clickOnMenu; // Error here
}(this, this.document));
The line causing the error is: menuLink.onclick = clickOnMenu; The error shown in chrome is TypeError: Cannot set property 'onclick' of null.
I don't understand why the menuLink variable is null. In Chrome console, when I type console.log(menuLink), the variable is not null and contains the DOM object in question.
I included my javascript file at the end of the visualforce page :
Note that the exact same code works fine on a local environment! (html instead of visualforce).
Thanks in advance for any help. Riadh