I have a javascript function that is called when a link is clicked. However I just want the function to run without the link redirecting. I have heard I should use return false but it doesn't work!
function hideaddclasses(e){
var element = document.getElementById("addclasses");
if(element.style.display=="none"){
element.style.display="";
}else{
element.style.display="none";
}
e.preventDefault();
return false;
}
Then for the html I simply have:
<a href='#' onclick='hideaddclasses()'>[ Hide ]</a>
Why does it still redirect?
I have a javascript function that is called when a link is clicked. However I just want the function to run without the link redirecting. I have heard I should use return false but it doesn't work!
function hideaddclasses(e){
var element = document.getElementById("addclasses");
if(element.style.display=="none"){
element.style.display="";
}else{
element.style.display="none";
}
e.preventDefault();
return false;
}
Then for the html I simply have:
<a href='#' onclick='hideaddclasses()'>[ Hide ]</a>
Why does it still redirect?
Share Improve this question asked Feb 7, 2012 at 3:55 Eric SmithEric Smith 1,3765 gold badges19 silver badges33 bronze badges 1- 1 The return false; may have to be in the "onclick" itself: onclick='hideaddclasses(); return false;' – Brad Commented Feb 7, 2012 at 3:56
2 Answers
Reset to default 7<a href='#' onclick='return hideaddclasses()'>[ Hide ]</a>
(Note the return
).
You can use e.preventDefault()