1

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>

0

4 Answers 4

4

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();
});
Sign up to request clarification or add additional context in comments.

Comments

0
var x = 0;

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

Comments

0

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

Comments

0

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();

});

Comments

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.