I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET request. While the population works as expected, there is an issue when trying to switch between active elements.
The first div, which showcases the Bootstrap example, switches the active element correctly. However, the second div, which I have customized, does not.
Below is the HTML code snippet:
<button id="boton1">TEST</button>
<div class="list-group col-md-3">
<a href="#" class="list-group-item active">
Cras justo odio
</a>
<a href="#" class="list-group-item">Dapibus ac facilisis in</a>
<a href="#" class="list-group-item">Morbi leo risus</a>
<a href="#" class="list-group-item">Porta ac consectetur ac</a>
<a href="#" class="list-group-item">Vestibulum at eros</a>
</div>
<div class="panel panel-default col-md-3">
<div class="panel-heading">Geolocation
<span class="pull-right"><span class="fa fa-globe"></span></span>
</div>
<div class="panel-body" style="height: 400px;">
<div class="list-group" id="ticker">
</div>
</div>
</div>
Here is the JavaScript code:
$(document).ready(function(){
var counter=0;
var alert;
$("#boton1").click(function() {
for(var i=0; i<5; i++){
counter++;
if (counter===1){
alert = "<a class='list-group-item active' ";
}else{
alert = "<a class='list-group-item' ";
}
alert+="href='#'>";
// Alert title
alert+="<h4 class='list-group-item-heading'>";
alert+="Alert #"+counter;
alert+="</h4>";
// Alert text
alert+="<p class='list-group-item-text'>";
alert+="Hello!";
alert+="</p>";
alert+="</a>";
$("#ticker").append(alert);
}
});
$('.list-group-item').on('click',function(e){
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active');
$(e.target).addClass('active');
});
});
You can view the fiddle here: http://jsfiddle.net/txfjjzsm/