Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .hide() only working half the time

This might look very obvious to some people, but I really could not figure out why something like this might be happening, so I'm looking for any help possible!

I have expanding rows, and each row should expand to show its details when clicked on, or when next button is pressed. They show and hide properly when clicked, but I cannot get it to work when next button is pressed.

This is the .js part:

var main = function() {

var curQuantity1 = 0;
var curQuantity2 = 0;
var curQuantity3 = 0;

$('.article').click( function() {
    $('.description').hide();
    $('.article').removeClass('current');
    $(this).children('.description').show();
    $(this).addClass('current');
});

$(".next1").click( function() {
    if (curQuantity1 + curQuantity2 + curQuantity3 == 3){
        console.log("Next clicked");

        var currentArticle = $('.current');
        var nextArticle = currentArticle.next();

        currentArticle.removeClass('current');
        nextArticle.addClass('current');

        $('.description').hide();
        $('.current').children('.description').show();
    } else {
        alert("총 3통을 골라주세요");
    }
});
...//code here takes care of updating curQuantity so they can add upto 3
};

$(document).ready(main);

I think pasting html code here might make it too long, but will do so if needed.

I am vaguely guessing that child might not be allowed to modify its parent class, but I could not find a way around it.

Thank you in advance for any help! I was getting stumped for the whole day :(

like image 971
nick.jw.park Avatar asked Nov 01 '22 05:11

nick.jw.park


1 Answers

Since .next1 is inside .article, when you click on the Next button, the click is also being sent to the article that contains it, because of event bubbling. So first the .next1 click handler is revealing the next item, then the .article click reveals the old article. The solution is to use event.stopPropagation() to stop the event from bubbling out:

$(".next1").click( function(e) {
    e.stopPropagation();
    if (curQuantity1 + curQuantity2 + curQuantity3 == 3){
        console.log("Next clicked");

        var currentArticle = $('.current');
        var nextArticle = currentArticle.next();

        currentArticle.removeClass('current');
        nextArticle.addClass('current');

        $('.description').hide();
        $('.current').children('.description').show();
    } else {
        alert("총 3통을 골라주세요");
    }
});
like image 60
Barmar Avatar answered Nov 12 '22 17:11

Barmar