Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a nested Bootstrap collapse element from firing .show() on the parent?

Here is a jsfiddle of my setup;

http://jsfiddle.net/7LBr5/1/

You'll notice I have indicator arrows on the parent accordion and a function that toggles them when the accordion shows and hides. The problem is that the inner collapse areas (used to hide product details) trigger the function that toggles the arrows on the parent. It seems that the .show() event must be firing on the parent collapse element when the child is actually the one collapsing.

How can I fix this so that the child collapse doesn't toggle the arrows on the parent?

Here is the code for my function;

$('.collapse').on('show', function(){
$(this).parent().find(".icon-chevron-right").removeClass("icon-chevron-right").addClass("icon-chevron-down");}).on('hide', function(){
$(this).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-right");});
like image 253
Jo Sprague Avatar asked Dec 16 '22 09:12

Jo Sprague


1 Answers

Just stop the event from propagating to the parent on the button click using event.stopPropagation, so that it doesn't trigger the click event on the accordion after executing the click event on the button.

$thisButton.click(function(e) {
      e.stopPropagation();
//.. Code follows

Demo

Also by the way you don't need to perform an each on the selector to bind the click event, instead just specify the selector for click event itself

$(".btn-switch").click(function (e) {
    e.stopPropagation();
    var $thisButton = $(this);
    $thisButton.toggleClass("btn-primary btn-danger");
    if ($(this).hasClass('btn-danger')) {
        $thisButton.html('<i class="icon-remove-circle icon-white"></i> Remove');
        $(this).parents('.thumbnail').find('.rental-count').val('1');
        $(this).parents('.thumbnail').find('input').change();
    } else {
        $thisButton.html('<i class="icon-ok-circle icon-white"></i> Add to Quote');
        $(this).parents('.thumbnail').find('input').val('');
        $(this).parents('.thumbnail').find('input').prop('checked', false);
        $(this).parents('.thumbnail').find('input').change();
    }
});
like image 68
PSL Avatar answered Dec 28 '22 09:12

PSL