I made a custom pager for my bxSlider. I want to change the original grey img
to the colored image when it is clicked and get class "green". While the clicked pager has class "green" and colored image, I want the other pager stay as the original gray image.
I got to the part where I can replace the original gray img
to green, and remove the class "green" of the siblings, however, even though the class "green" is removed from the siblings, it still remains as colored img
instead of going back to the original grey as if removeClass("green")
is not working.
HTML:
<ul id="slidePager">
<li class="col-md-2 b-conts1">
<a href="#" data-slide-index="0">
<img src="img/benefit-lowcost-g.png" class="b-cost" alt="low cost icon" >
</a>
</li>
<li class="col-md-2 b-conts2">
<a href="#" data-slide-index="1">
<img src="img/benefit-logistic-g.png" class="b-logistic" alt="logistics icon" >
</a>
</li>
</ul>
jQuery:
$(function(e){
$('.b-conts1').on('click', function(e){
e.preventDefault();
$(this).addClass('green').siblings().removeClass('green');
if($(this).hasClass('green')){
$('.b-cost').attr('src','/img/benefit-lowcost-c.png');
} else {
$('.b-cost').attr('src','/img/benefit-lowcost-g.png');
};
});
$('.b-conts2').on('click', function(e){
e.preventDefault();
$(this).addClass('green').siblings().removeClass('green');
if($(this).hasClass('green')){
$('.b-logistic').attr('src','/img/benefit-logistic-c.png');
} else {
$('.b-logistic').attr('src','/img/benefit-logistic-g.png');
};
});
});
As UncaughtTypeError indicated, once you stick the green class on, it's pointless to check if it's there. Instead, toggle the images you want -- if you're changing the image in both the cost and logistic image, then you'll simply set them both in each case.
$(function(e) {
$('.b-conts1').on('click', function(e) {
e.preventDefault();
$(this).addClass('green').siblings().removeClass('green');
// Remove the if bit here -- instead, simply set the images
// for BOTH cost and logistic. Same below.
$('.b-cost').attr('src', '/img/benefit-lowcost-c.png');
$('.b-logistic').attr('src', '/img/benefit-logistic-g.png');
});
$('.b-conts2').on('click', function(e) {
e.preventDefault();
$(this).addClass('green').siblings().removeClass('green');
$('.b-cost').attr('src', '/img/benefit-lowcost-c.png');
$('.b-logistic').attr('src', '/img/benefit-logistic-g.png');
});
});
ul {
width: 200px;
}
li {
background-color: #ccc;
}
.green {
background-color: #9c9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="slidePager">
<li class="col-md-2 b-conts1">
<a href="#" data-slide-index="0">
<img src="img/benefit-lowcost-g.png" class="b-cost" alt="low cost icon">
</a>
</li>
<li class="col-md-2 b-conts2">
<a href="#" data-slide-index="1">
<img src="img/benefit-logistic-g.png" class="b-logistic" alt="logistics icon">
</a>
</li>
</ul>