susanta kumar muduli susanta kumar muduli - 4 months ago 15
Javascript Question

how add class in selected images in slide show?

When I click on thumb image, I want to selected that thumb image, but here when I click other thumb image previous thumb image remain selected

CSS Code:

.imgStyle:hover {
border-color: black;
}
.imgStyle {
height: 100px;
width: 100px;
border: 2px solid grey;
}
.active {
border-color: red;
}


//js code

$(document).ready(function () {
$('#divContainer img').on('click', function () {

$(this).addClass('active');

var imgURl = $(this).attr('src');

$('#mainImage').fadeOut(1000, function () {
$(this).attr('src', imgURl);
}).fadeIn(1000);

});
});


HTML:

<img id="mainImage" src="images/Chrysanthemum.jpg" width="540" height="500" style="border:3px solid grey">

<br/>
<div id="divContainer">
<img class="imgStyle" src="images/Chrysanthemum.jpg" />
<img class="imgStyle" src="images/Desert.jpg" />
<img class="imgStyle" src="images/Hydrangeas.jpg" />
<img class="imgStyle" src="images/Jellyfish.jpg" />
<img class="imgStyle" src="images/Koala.jpg" />
</div>

Answer

Remove active class from siblings of the clicked image

$(document).ready(function() {
  $('#divContainer img').on('click', function() {
    $(this).addClass('active').siblings('img').removeClass('active');
    var imgURl = $(this).attr('src');
    $('#mainImage').fadeOut(1000, function() {
      $(this).attr('src', imgURl);
    }).fadeIn(1000);
  });
});
.imgStyle:hover {
  border-color: black;
}
.imgStyle {
  height: 100px;
  width: 100px;
  border: 2px solid grey;
}
.active {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="mainImage" src="images/Chrysanthemum.jpg" width="540" height="500" style="border:3px solid grey">
<br/>
<div id="divContainer">
  <img class="imgStyle" src="images/Chrysanthemum.jpg" />
  <img class="imgStyle" src="images/Desert.jpg" />
  <img class="imgStyle" src="images/Hydrangeas.jpg" />
  <img class="imgStyle" src="images/Jellyfish.jpg" />
  <img class="imgStyle" src="images/Koala.jpg" />
</div>