最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to prevent my button's onclick for5 seconds - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited May 4, 2012 at 16:35 j08691 208k32 gold badges269 silver badges280 bronze badges asked May 4, 2012 at 16:23 ilyes kooliilyes kooli 12.1k14 gold badges55 silver badges81 bronze badges 1
  • Telling us why will help us figure out the best solution for you. – Thinking Sites Commented May 4, 2012 at 16:28
Add a ment  | 

5 Answers 5

Reset to default 5

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/KX5g7/1/

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

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

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

​DEMO

$(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);
});​

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'); });)

发布评论

评论列表(0)

  1. 暂无评论