Rasmus Hjorth Lüdeking Rasmus Hjorth Lüdeking - 5 months ago 24
jQuery Question

Event fire twice

Upon request, the button to click, to fire the event is the wide-ass orange button

this fire is suppose to add 12 vh to the height of #pfcontainer_inner_friends_list, and then upon 2nd click remove the height again

By the way; I'm not looking for a solution that does not entail ADDING or SUBTRACTING the height. The height of the element has to stay on 10.2vh, and the fires, HAVE TO, add or subtract a given height.

http://jsfiddle.net/zy73nd2c/

In the fiddle above, I've tried showcasing how my jQuery is firing twice upon click. How do i fix this?

$(function () {
$('.click-nav1 > ul').toggleClass('no-js js');
$('.clicker1').click(function (e) {
$('.click-nav1 .js ul').slideToggle(200);
$('.clicker1').toggleClass('active');
e.stopPropagation();
});
$('.clicker1').click(function () {
if ($('.click-nav1 .js ul').is(':visible')) {
$('.click-nav1 .js ul', this).slideUp();
$('.clicker1').removeClass('active');
}
});
});
$(function () {
$('.clicker1').click(function () {
if ($('.click-nav1 .js ul').is(':visible')) {
$("#pfcontainer_inner_friends_list ul").animate({"height" : "+=12vh"});}
});
});
$(function () {
$('.clicker1').click(function () {
if ($('.click-nav1 .js ul').is(':hidden')) {
$("#pfcontainer_inner_friends_list ul").animate({"height" : "- =12vh"});}
});
});

Answer

Apparently, .is(":visible") and .is(":hidden") can have the same value at a certain time of evaluation.

Possible work-around: Toggle a class on the $element of choice, then use $element.hasClass(...) to decide whether to increase or decrease height.

This works as js in your jsfiddle:

$(function () {
    $('.click-nav1 > ul').toggleClass('no-js js');
    $('.clicker1').click(function (e) {
        $('.click-nav1 .js ul').toggleClass('vis').slideToggle(200);
        $('.clicker1').toggleClass('active');
        e.stopPropagation(); 
    });
    $('.clicker1').click(function () {
        if ($('.click-nav1 .js ul').is(':visible')) {
            $('.click-nav1 .js ul', this).slideUp();
            $('.clicker1').removeClass('active');
        }
    });
    $('.clicker1').click(function () {
        var dh = $('.click-nav1 .js ul').hasClass('vis') ? "+=12vh" : "-=12vh";
        $("#pfcontainer_inner_friends_list ul").animate({"height" : dh});
    });
});
Comments