Reputation: 43
I use the following code for changing the icon in nested bootstrap collapsible elements (accordion). But when I click a nested element - e.g. the third level - the icons at the second and first parent elements will also be changed. I only want my click action to affect the element it was directly invoked on.
$(document).ready(function() {
$('.collapse').on('show.bs.collapse', function() {
var id = $(this).attr('id');
$('a[href="#' + id + '"] .panel-title span').html('<i class="glyphicon glyphicon-chevron-down"></i>');
});
$('.collapse').on('hide.bs.collapse', function() {
var id = $(this).attr('id');
$('a[href="#' + id + '"] .panel-title span').html('<i class="glyphicon glyphicon-chevron-right"></i>');
});
});
How can i change only the icon of the current element without the parent element?
Upvotes: 1
Views: 139
Reputation: 18233
The problem you're noticing isn't due to incorrect ID referencing, it's actually due to the event being triggered on the parent elements as well. You can fix this by preventing the event from 'bubbling' up the DOM tree (i.e. being triggered on all parent elements of your target element).
Prevent the event from bubbling up to the parent elements by calling stopPropagation
on the event object.
From the jQuery docs:
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$(document).ready(function() {
$('.collapse').on('show.bs.collapse', function(e) {
e.stopPropagation();
var id = $(this).attr('id');
$('a[href="#' + id + '"] .panel-title span')
.html('<i class="glyphicon glyphicon-chevron-down"></i>');
});
$('.collapse').on('hide.bs.collapse', function(e) {
e.stopPropagation();
var id = $(this).attr('id');
$('a[href="#' + id + '"] .panel-title span')
.html('<i class="glyphicon glyphicon-chevron-right"></i>');
});
});
Upvotes: 2