I want to click a table element and to have it do x the first click and if clicked again perform Y
<td class='p' id='e1' onclick="myFunction2()"><img src='person2.png'/></td>
Thats what I have for my HTML for one click just now, but I wish to change that so that an item can be selected, then if clicked again for a deselect it would then trigger a different function.
Using a
state
variable. Thestate
variable will swap between the values0
and1
on each click. Making use ofstate
we can execute the corresponding function infn
array.Also, it's preferably to use proper event binding than inline JavaScript.
I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:
This uses jQuery's
.data
feature to store the button's click state in the button element itself.Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:
If the
.on
call and thestate
variable declaration are inside a jQuerydocument.ready
handler that would have the same effect.You could create a new atribute on the HTML element named, for example, "clickCount", and use it inside your event handler as a counter.
Let's say you have a button like this one:
And you have a function like this:
Every time you click the button, you'll see an alert with the number of clicks you've made.
You can use the same method and apply it to your case.
demo: http://jsfiddle.net/HJwJf/
Link the toggle method with;
Pretty basic, let me know if this is close to what you want.
http://jsfiddle.net/WNJ75/6/
.