Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the button's function with jQuery?

This might be a silly question but I just can't get it right. I can change the button's function with ordinary JavaScript but not with jQuery. I'm aiming for a very simple text-resize button. This button needs two different functions; one that makes the text bigger and changes the click function to the other function, and this other function makes the text smaller and changes the click function to the first function again. Since the same button will be used for both enlarging and reducing the text sixe, I need this to work. I'm working on a school project right now and we have to use only jQuery/jQuery UI for this assignment.

With ordinary 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 do I achieve the same thing with jQuery?

like image 776
mizuki Avatar asked Mar 21 '13 09:03

mizuki


2 Answers

Something like the below code would 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)
}

Working example here: http://jsfiddle.net/K3Xk4/

like image 110
Ravi Y Avatar answered Sep 23 '22 13:09

Ravi Y


You don't need to change the handler every time. You can use a function and a variable to check if you already clicked 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
}
like image 28
Tim S. Avatar answered Sep 20 '22 13:09

Tim S.