Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
Dear All,
A simple one I am sure but it has been a long week.
This is the simple code I am wiring for a menu, why do I get a function undefined error for my close / open navs when I click the various items (the click works with a simple console.log)?
html="<div id=''#' + divName' class='sidenav' > "
html = html+"<a href='javascript:void(0)' id='closebtn' class='closebtn' onclick='closeNav()'>×</a>"
html = html+"<a href='#'>About</a>"
html = html+" <a href='#'>Services</a>"
html = html+" <a href='#'>Clients</a>"
html = html+" <a href='#'>Contact</a>"
html = html+"</div>"
html = html+"<span style='font-size:30px;cursor:pointer' onclick='openNav()'>open</span>"
/* Set the width of the side navigation to 250px */
function openNav() {
document.getElementById("'#' + divName").style.width = "250px";
}
/* Set the width of the side navigation to 0 */
function closeNav() {
document.getElementById("'#' + divName").style.width = "0";
}
_this.Element.innerHTML = html;
I'm a little rusty here, but shouldn't the HTML definition be:
html="<div id='#" + divName + "' class='sidenav'>"
And the call be:
document.getElementById("#" + divName).style.width = "250px";
I am assuming that divName is a variable.
I don't think so, purely because it displays OK and even if I simplify the function to a console.log, it won't call it
That isn't to say that you are not correct of course, I just don't think it is the cause (buit I will try it )
The HTML will work, but I think the div name is actually something like #'+divName (literally and no leading quote) and getElementById is looking for '#'+divName (literally and with leading quote). Or at very least, getElementById is returning undefined and then the .style.width properties also undefined....
Anyway, I last did much DOM/js programming about 5 years ago, so I am very rusty
Yeah I am trying to self-learn it and its a bit of a headache!
So just to simplify it right out:
this works:
_this.Element.innerHTML = "<span style='font-size:30px;cursor:pointer' onclick='console.log(123)'>open</span>"
Whereas this doesn't (testClick is undefined)
_this.Element.innerHTML = "<span style='font-size:30px;cursor:pointer' onclick='testClick'>open</span>"
function testClick(){
console.log(123);
}
So the innerHTML object can't see the function.... I mean I get local and global scope etc within JS but not quite how that fits with the innerHTML element!