Given the following example code I want to set the onclick event to a function which I declare in the same method (no function in global scope):
<HTML>
<HEAD>
<Title>Title</Title>
</HEAD>
<body>
<img id="img" class="std" src="http://www.free-animated-pictures.com/bug_crawls_on_screen.gif"/>
<script type='text/javascript'>
var i = document.getElementById("img");
var func = function(){
var i = document.getElementById("img");
if(i.className === "std"){
i.className = "hid";
i.style.display = "none";
}
else if(i.className === "hid"){
i.className = "std";
i.style.display = "block";
}
};
//func = func.toString();
//func = func.replace("function ()", "")
document.body.setAttribute("onclick", func);
</script>
</body>
</HTML>
If I use the code as is I only get the following error when the event is fired:
Uncaught SyntaxError: Unexpected token (
If instead I take the string of the function and remove the function part of it, the script works as expected:
func = func.toString();
func = func.replace("function ()", "")
Why is that so? Is there a better way? Obviously I can't declare the function without the function part, so what's the point in removing it again?
document.body.onclick = funcdon't usesetAttributeit's not an attribute, well it can be an HTML one but you don't do that from JS.