Nave Tseva
Nave Tseva

Reputation: 878

Can't execute a jQuery function more than once

I have the following function:

$('#edit').on("click", function () {
    $('#edit').text('click1');
    $('table a').click(function (e) {
        e.preventDefault();
    });
    $('table a').css("cursor", "default");

        }
    });
    $('#edit').click(function () {
        $('#edit').unbind();
        $('#edit-message-placeholder').empty();
        $('#edit').text('click2');
        $("table tbody").sortable("disable");
        $('table a').unbind()
        $('table a').css("cursor", "auto");

    });
});

On first click, I want it to change the text of div#edit. On second click, it will change the text to something else. On third click, the function will behave as though it was clicked the first time.

I tried to find a solution online, but found nothing useful.

Upvotes: 0

Views: 823

Answers (2)

brainless coder
brainless coder

Reputation: 6430

Try this -

Use the data property to temporarily save the counter data

<button id="edit" data-count="1">1</button>


function doWork(val){
    alert(val);
};
$('#edit').on("click", function () {

    if($(this).data('count') == ""){
        $(this).data('count') = 1;
    }
    var count = parseInt($(this).data('count'));
    if (count == 1){
        doWork(count);
    }else if (count == 2){
        doWork(count);
    }else if (count == 3){
        doWork(count);
    }
    count += 1
    count = count >= 4 ? 1: count;
    $(this).data('count', count);
    $(this).html($(this).data('count'));
});

Here is the jsfiddle - http://jsfiddle.net/pt3zE/1/

Upvotes: 2

royhowie
royhowie

Reputation: 11171

The problem is that you're approaching this incorrectly. You don't need to bind/unbind event handlers. You only need one event handler that alternates in functionality:

JavaScript

var isOkay = true;
$("p").click(function () {
    if (isOkay) {
        $(this).text("1st click");
    } else {
        $(this).text("2nd click");
    }
    isOkay = !isOkay;
})

HTML

<p>Click me!</p>

Every time the <p> is clicked, it performs an action and then switches the value of a boolean variable, isOkay. This means that it will alternate between the if and else block. Note that the isOkay variable is held outside the scope of the $("p").click(...) event handler.

fiddle

Upvotes: 2

Related Questions