Change button function with jQuery?

This may be a stupid question, but I just can't understand. I can change the button function using normal JavaScript, but not with jQuery. I am aiming for a very simple text resize button. This button requires two different functions; one that makes the text bigger and changes the click function to another function, and this other function reduces the text and again changes the click function to the first function. Since the same button will be used to both enlarge and shorten the sixe text, I need this to work. I am currently working on a school project, and for this purpose we should use only jQuery / jQuery UI.

With regular JavaScript, it would be something like this:

var button = document.getElementById('click-button'); button.onclick = firstClick; function firstClick (){ button.onclick=secondClick; } function secondClick(){ button.onclick=firstClick; } 

How to achieve the same result using jQuery?

+4
source share
4 answers

Something like the code below will work.

 $("#click-button").on('click', firstClick) function firstClick() { alert("First Clicked"); $("#click-button").off('click').on('click', secondClick) } function secondClick() { alert("Second Clicked"); $("#click-button").off('click').on('click', firstClick) } 

A working example is here: http://jsfiddle.net/K3Xk4/

+10
source

You do not need to change the handler every time. You can use the function and variable to check if you pressed the button (or not).

 var even = false; $('#click-button').click(function() { if(even) { doEven(); } else { doOdd(); } even = !even; }); function doOdd() { // first click, third click, fifth click, etc } function doEven() { // second click, fourth click, sixth click, etc } 
+3
source

You can just do it

 <button id="click-button">test</button> var flag = 1; $("#click-button").click(function(){ if(flag == 2){ secondClick(); flag = 1; }else{ firstClick(); flag = 2; } }); function firstClick(){ alert("First Click."); } function secondClick(){ alert("Second Click.") } 

here http://jsfiddle.net/K3Xk4/5/

+1
source

I would go with custom events and data processing:

 $('#click-button').on({ firstClick : function() { // do something alert(111); // switch back $(this).data('nextClick', 'secondClick'); }, secondClick : function() { // do something alert(222); // switch back $(this).data('nextClick', 'firstClick'); }, click : function() { var nextClick = $(this).data('nextClick') || 'firstClick'; $(this).trigger( nextClick ); } }); 

Example here: http://jsfiddle.net/psycketom/nbSMg/

You save all the time with the same area of ​​elements, no need to define variables outside functions.

It may be a bit overkill, but the easiest way to maintain.

0
source

All Articles