I have a HTML anchor that when clicked should make a div slide up or down (I call JQuery\'s .slideToggle(); function);
My Problem: When
I see a lot of answers that involve work-arounds, but none that hit the heart of the issue. The why behind what you're doing is not working, and why it often does work.
You're using javascript:XXX as the value for the href, hypertext source link, attribute on your anchor tag. Where XXX is some piece of javascript code, an expression, such as a function call.
When using this notation, the XXX code is first evaluated. If the expression results in a value, then most browsers will clear the page and display only the resultant value.
For example,
Click here! will result in 2 being displayed.
Similarly, this could be rewritten with a function to produce the same results:
function addTwo() {
return 1+1;
}
Click here! (expected output 2)
For most browsers, if the XXX code is evaluated and does not result in a value, then it has nothing to display -- as such, it will stay on the same page. So, there's a few ways to achieve this behavior.
There is no result left over during assignment.
A.
function addTwo2() {
addTwo();
}
Click Here!
B. Same thing, but all inline:
C. Same thing, but with the ! idiom you'll often see. (Same logical meaning, just uses the not operator to achieve less characters used):
We could instead do what is referred to as hooking in most functional programming languages:
function addTwo() {
alert( "sfsf" );
return 1+1;
}
var x = addTwo;
addTwo = function() {
x();
}
Lastly, if your function or expression does not need to return anything, simply don't do it in that function.
So in summary:
When your anchor using a javascript: href is clicked, the javascript code after javascript: is first evaluated, if it results in a value the browser will display only the result, otherwise the browser will stay on the page it currently is on since it has no value to display.