I would like one button to perform two jquery functions. One on the first click then the other on the second click. Here is the code for the two buttons. Is there a way to combine the functions?
<input type="button" value="View Page" onclick="ViewPage()" />
<script type="text/javascript">
function ViewPage() {
example_animate('-=50%');
$("#mainContent").toggle();
}
</script>
<input type="button" value="View Menu" onclick="ViewMenu()" />
<script type="text/javascript">
function ViewMenu() {
example_animate('+=50%');
$("#mainContent").toggle();
}
</script>
On click of the button have a function which decides which function to call according to number of times. So first time it will execute function one and second time onwards it will execute function two . Show activity on this post. The simplest way is defining an extra variable to false (or true , of course).
The two methods are to 1) create a new form, put the correct results in that (i.e. use a hidden field with the correct "submit value"), and then submit() it or 2) create an AJAX request (i.e. $. AJAX) and supply the desired data.
You can add an onclick attribute to the button that changes the display to block.
Try something like this - DEMO
var action = 1;
$("input").on("click", viewSomething);
function viewSomething() {
if ( action == 1 ) {
$("body").css("background", "honeydew");
action = 2;
} else {
$("body").css("background", "beige");
action = 1;
}
}
So in your case it will be
function viewSomething() {
if ( action == 1 ) {
example_animate('-=50%');
action = 2;
} else {
example_animate('+=50%');
action = 1;
}
$("#mainContent").toggle();
}
Another way using one
method, both will fire only once
$("input").one("click", viewSomething);
function viewSomething()
{
$("body").css("background", "honeydew");
$("input").one("click", function(){ // on can be used
$("body").css("background", "beige");
});
}
DEMO.
Update: If you want to keep the second handler alive then replace one
with on
like this one.
You can also assign a name to html element..
<input type="button" value="Click me" onclick = 'viewSomething(this)'/>
<script>
function viewSomething(e){
//First time click
if(e.name != 'Click'){
e.name = "Click";
<!--do whatever..-->
}//end if
//When click it again..
else if(e.name == 'Click'){
e.name = "Unclick";
<!--do whatever-->
}//end else
}//end function
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With