Pergunta

I have an array in my js file that loads images into html for a slideshow and for thumbnail navigation. The slideshow img src matches one of the thumbnail image src attributes every 4 seconds. This timing is based off of a setInterval.

I would like to continually check if the slideshow img src matches the thumbnail img src and then add a class of active to both. I have been able to add the class to the main slideshow and all of the thumbnails but I can't seem to be able to only add the class to ONLY the img elements with the matched src attributes

<div class="slideshow">
<!-- this img src attribute changes on a setInterval and matches one of the .imageHolder img src attributes at a time. I would like to addClass to img elements that have the same src and remove when they no longer match-->
<img class="slideshowimg" alt="" src="imgs/slide3_470hx690w.jpg" style="opacity: 1;">
</div>
<div class="description" style="opacity: 1;">
    <h2>LOREM IPSUM BLAH BLAH BLAH</h2>
    <p>lorem ipsum blah blah blah</p>
    <a href="#" class="btn readmore">Read More</a>
</div>
<a href="#" class="btn prev">Previous</a>
<a href="#" class="btn next">Next</a>
<div class="window">
    <div class="imageHolder" style="width: 690px;">
        <img src="imgs/slide1_470hx690w.jpg">
        <img src="imgs/slide2_470hx690w.jpg">
        <img src="imgs/slide3_470hx690w.jpg">
        <img src="imgs/slide4_470hx690w.jpg">
        <img src="imgs/slide5_470hx690w.jpg">
    </div>
</div>
Foi útil?

Solução

I thought it would be as simple as $('img[src=URL]'), however, thorough testing has found this does not work 100% of the time. Thus I ended up finding your possible solution in jQuery's .filter() function. .filter() allows you to weed the needle out of the stack based on your own callback.

I also made use of the images .load() event. If the image is successfully loaded into the main slideshow img tag, it will fire a .load() event thus allowing you to make do work after the image has loaded. So you could do something like:

$('.slideshowimg').on('load', function(e) {
    $('img.active').removeClass('active');
    var src = $(this).addClass('active').prop('src');
    $('img').filter(function(e) { return $(this).prop('src') == src; }).addClass('active');
});

Example

Outras dicas

You can do that with following function. I assume that

  1. You are already know src
  2. You are able to select which images to be change as active/passive

First, remove active class from all thumbs, and add it to specific one

function change(src) {
    $(".imageHolder img").each(function(){
        $(this).removeClass("active");
    });
    $('img[src="' + src + '"]').addClass("active");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top