jarrett owen
jarrett owen

Reputation: 87

jQuery click function firing at the same time

I have two click functions that seem to be firing at the same time. I need the second to only happen after the first.

So the first slideDown is working fine but once that has finished I want it to stop, and then the slideUp to happen own the .close class is clicked.

$(".trigger").click(function() {
    $(".mobileWrap").slideDown(500);
    $(".mainContentBg").addClass("height", 1000);
    $(".trigger").text("Read less");
    $(".trigger").addClass("close");
    $(".close").removeClass("trigger");
});
$("body").on("click", ".close", function() {
    $(".mainContentBg").removeClass("height", 1000);
    $(".mobileWrap").slideUp(1000);
    $(".trigger").addClass("trigger");
    $(".trigger").text("Read more");
});

http://jsfiddle.net/6hvZT/648/

Thanks

Upvotes: 1

Views: 84

Answers (1)

Shaunak D
Shaunak D

Reputation: 20646

Problem with your code :

As the class close is being added, the delegated click is being triggered.

Updated Fiddle

If your wish is to toggle More-Less;You can just use toggleClass and slideToggle instead of two different click events,slideUp/slideDown and addClass/removeClass.

Below is the shortened code.

$(".trigger").click(function() {
    $(".mobileWrap").slideToggle(500);
    $(".mainContentBg").toggleClass("height", 1000);
    $(".trigger").text(function(){
        return this.innerText === "Read less"? "Read more":"Read less"
    });
});

Also, if you have multiple such instances, inside the handler it is better to use $(this) instead of $('.trigger')

Upvotes: 1

Related Questions