ilyes kooli
ilyes kooli

Reputation: 12043

How to prevent my button's onclick for 5 seconds

I have something like:

<button id="button" onclick="alert('Hi')">a button</button>


I want to deactivate the button onclick action, let's say for 5 seconds after the page loads.
Note: I don't want to make the button disabled, just want it's onclick action not to work untill 5 seconds.

Upvotes: 2

Views: 1088

Answers (5)

Andrea Turri
Andrea Turri

Reputation: 6500

$(function(){
        $('#button').unbind('click');
        setTimeout(function(){
            $('#button').bind('click');
        }, 5000);
    });​

EDIT:

This seems to not unbind the event as Rocket told, so, I think that a good solution could be to remove the attribute that fire the event:

$(function(){
    $('#button').attr('onclick', '');
    setTimeout(function(){
        $('#button').attr('onclick', 'alert("Hi")');
    }, 5000);
});​

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227190

You can simply just remove the onclick attribute, and then put it back 5 seconds later.

var onClickFunc = $('#button').prop('onclick');
$('#button').removeProp('onclick');
setTimeout(function(){
    $('#button').click(onClickFunc);
}, 5000);

DEMO: http://jsfiddle.net/KX5g7/1/

Upvotes: 5

yoozer8
yoozer8

Reputation: 7489

To do that, don't put the onclick inline.

In your $(document).ready(...) function, use setTimeout to wait 5 seconds with a callback function to set the onclick ($('#button').click(function(btn) { alert('Hi'); });)

Upvotes: 0

ilyes kooli
ilyes kooli

Reputation: 12043

$(function(){
    $('#button').attr('savedclick', $('#button').attr('onclick')).removeAttr('onclick');  
    setTimeout(enableButton, 5000);    
});

function enableButton(){
    $('#button').attr('onclick', $('#button').attr('savedclick')).removeAttr('savedclick');
}

DEMO

Upvotes: 1

jaredhoyt
jaredhoyt

Reputation: 1575

Use jQuery to bind the event after a timeout of 5 seconds.

setTimeout(function(){
    $('#button').click(function(){
        alert('Hi');
    });
}, 5000);

Upvotes: 4

Related Questions