Rifet Gazdić
Rifet Gazdić

Reputation: 83

Prevent jquery from multiple click function

Is there a chance to adjust my code so when someone clicks button code would be executed only once? Not as many times as user clicks that button. Thanks
HTML

<button class="click_me">Click</button>
<div class="example">Some text</div>

CSS

.example{
    width:100px;
    padding:5px 5px;
    background:skyblue;
    color:white;
    display:none;
}

JQUERY

$(".click_me").click(function(){
    $(".example").slideDown();
    $(".example").delay("2000").slideUp();
});

Also check out my Fiddle!

$(".click_me").click(function() {
  $(".example").slideDown();
  $(".example").delay("2000").slideUp();
});
.example {
  width: 100px;
  padding: 5px 5px;
  background: skyblue;
  color: white;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click_me">Click</button>
<div class="example">Some text</div>

Upvotes: 1

Views: 178

Answers (4)

mininoz
mininoz

Reputation: 5958

You can disable the button after click as well. I prefer this way because users will know that the button can not be clicked any more.

$(".click_me").click(function(){
    $(this).prop("disabled",true);
    $(".example").slideDown();
    $(".example").delay("2000").slideUp();

});

Upvotes: 0

Timotheus0106
Timotheus0106

Reputation: 1586

as the user wrote before you can use the one function. but then the function really only got executed once.. and its not possible to execute it again.

adding and removing a class will do the trick.

$(".click_me").click(function(){
    if(!$(this).hasClass('locked')) {
        $(".example").slideDown();
        $(".example").delay("2000").slideUp();
        $(this).addClass('locked');
    }
});

in this case you can for instance unlock the click by removing the class from the element. in your case after 2s... like:

$(".click_me").click(function(){
    $(this) = $this;
    if(!$this.hasClass('locked')) {
        $(".example").slideDown();
        $(".example").delay("2000").slideUp();
        $this.addClass('locked');
    }
    setTimeout(function(){
        $this.removeClass('locked')
    }, 2000);
});

greetings timmi

Upvotes: 0

serek
serek

Reputation: 103

var x = 0;

$(".click_me").click(function(){
    if ( ++x === 1 ) {
        $(".example").slideDown();
        $(".example").delay("2000").slideUp();
    }
});

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240868

You could use the .one() method. In doing so, the function is only executed once.

From the jQuery docs:

The .one() method will attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Updated Example

$(".click_me").one('click', function(){
    $(".example").slideDown();
    $(".example").delay("2000").slideUp();
});

Upvotes: 4

Related Questions