WorklightBeginner WorklightBeginner - 6 months ago 20
jQuery Question

Jquery want to override function on button click

I already have a jquery .on() function in which click event is passed on a button.

I want to restrict user from clicking button more than 1 but i dont want to alter current function instead write new function



$('button').on('click',function(){

alert('hi');

});



$('button').click(function(event){

var count = 0;
count = count + 1;

if(count>1){
event.preventDefault();
console.log('dont call alert');
}

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>
Click Me !
</button>




Answer

I think you are looking for something like following.

$('button').on('click', function () {
    alert('hi');
});


var isCliked = true;
$('button').click(function () {
    $('button').off('click');

    isCliked && $('button').click(function() {
        console.log('dont call alert');
        isCliked = false;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
    Click Me !
</button>