shabbir.rang
shabbir.rang

Reputation: 279

Make the CSS positioning to be changed only once onclick

Code :

    $(document).ready(function(){
    $("#main_div").bind('click', function(e){
    var x = event.pageX-document.getElementById("main_div").offsetLeft;
    var y = event.pageY-document.getElementById("main_div").offsetTop;


    if(...)
    {
    $("#container-5").css({"top":y,"left":x});
    $(this).unbind('click');
    e.stopPropagation();

    }
    else if(...)
    {

    ....

    });
 });

When i click on main_div it checks for if function and proceeds. Css of container-5 is changed too. Now once the css is changed i don't want it to keep changing on main_div clicks. So i tried $(this).unbind('click'); But this doesnt help because i want main_div to be clicked as many times as i want so that i can perform other functionalities. Help really appreciated.

Upvotes: 0

Views: 70

Answers (2)

mayrs
mayrs

Reputation: 2377

An other way, maybe the more elegant one, would be firing the onclick handler only once using jQuery's .one() method. You would implement it as follows:

$("#main_div").one('click', function(e) {
    //the rest of your code
});

Note that this saves you at least 4 lines of code!

Upvotes: 3

maxedison
maxedison

Reputation: 17553

Just add an additional if statement inside the callback function that will be true the very first time and false forever afterwards:

var hasBeenClicked = false;
$("#main_div").bind('click', function(e){
    if(!hasBeenClicked){
        hasBeenClicked = true;
        ...
        //the rest of your code
        ...
    }
});

Upvotes: 1

Related Questions