I have these two javascript functions that change a background and show and hide fields, however it only works once for each button
function showabout(){
hidecontact = document.getElementById("contactus");
hidecontact.style.display = "none";
hide.style.backgroundImage = "url(aboutus.jpg)";
showabout = document.getElementById("aboutus");
showabout.style.display = "inline";
showabout.style.cssFloat = "left";
secbuttons.style.paddingLeft = "670px";
}
function showcontact(){
hideabout = document.getElementById("aboutus");
hideabout.style.display = "none";
hide.style.backgroundImage = "url(contact.jpg)";
showcontact = document.getElementById("contactus");
showcontact.style.display = "inline";
showcontact.style.cssFloat = "left";
secbuttons.style.paddingLeft = "670px";
}
<font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showabout()"> </h2></font>
<font color="#33FF66"><h2 style="cursor:pointer" onclick="showcontact()"> </h2></font><br />
<font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showcontact()"> </h2></font>
The three H2s are the lines causing the errors. It says “uncaught type error, object is not a function”.
Your problem is that you’re redefining
showaboutandshowcontact— your functions — to refer to HTML elements.These two code snippets:
and
both set the variable
window.showabout. The first one assigns a function towindow.showabout, and the latter assigns an HTML element towindow.showabout.Because you don’t use the
varkeyword to declare the variables in your functions,showabout = document.getElementById("aboutus")reassignsshowcontactto refer to that element instead of the function you’re defining. So then when you try to callshowcontact()a second time, it doesn’t work becauseshowcontactis no longer a function.The easy fix is actually an all-around good rule whenever you’re writing JavaScript:
Always declare your variables
There’s also a second lesson here:
Give your variables descriptive names
Although your code will work if you just declare the
showaboutvariable ahead of time, it will still be confusing to read. The function and the element it shows should have different names. Say, call the functionshowAboutBoxand the box it showsaboutBox. This way there’s no room for confusion — either by you or the language — about which thing you’re referring to.