0

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 don't 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>

2
  • You can use jQuery .one(): api.jquery.com/one Commented May 30, 2016 at 15:37
  • I already have a .on() function written in another file and i dont have access to that file ... so want to override it Commented May 30, 2016 at 15:42

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

JQuery off() method remove event handler of element. You can remove click event of button when it clicked. Using this work, button click event fired only once.

$("button").click(function(event){
    alert();
    $(this).off("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>

Comments

0

You can use jQuery .one() method:

$('button').one('click', function() {
    alert('hi');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Click Me !</button>

1 Comment

I already have a .on() function written in another file and i dont have access to that file ... so want to override it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.