Search code examples
jqueryhtmlimagerel

jquery change all src to rel


Im trying to mouse over an image and have all the images turn to the one image I'm mousing over. Which I have accomplished.

When I mouseout I want the images to go back to normal and I can't figure that out.

I'm trying to use the rel selector but in the solution I have now, when I mouseout all the images take the rel of the first image instead of everything just going back to normal.

Here is my HTML

<div id="container">
        <header id="masthead"><h1>Swap All</h1></header>
        <div id="stage">
            <div id="gallery">
                <img class="photo" rel="_images/image1.jpeg"  src="_images/image1.jpeg"  />
                <img class="photo" rel="_images/image2.jpeg"  src="_images/image2.jpeg"   />
                <img class="photo" rel="_images/image3.jpeg"  src="_images/image3.jpeg"   />


        </div>

here is my JS

    function grabIt(){

        var thisImageSrc = this.src;

        $('.photo').attr('src', thisImageSrc);



    }


    function letItGo() {

        var theRel = $('.photo').attr('rel');

        $('#gallery img').attr( 'src', theRel);

        console.log(theRel);
    }


        $('.photo').mouseover(grabIt);
        $('.photo').mouseout(letItGo);

Solution

  • Try this:

    function letItGo() {
        $('#gallery img').each(function() {
            //option#1: pure JS
            this.src = this.rel;
            //option#2: jQuery (I'll leave this in as an option because the OP used this himself and might prefer it even though it is not necessary)
            $(this).attr('src',$(this).attr('rel'));
        });
    }
    

    To be clear: you only need one option; if you want to use pure JS, remove option#2 from the code. And vice versa.


    What you tried doesn't work because you stored the rel-tag of only the first photo into var theRel. This line var theRel = $('#gallery img').attr('rel');, even if there are more elements that match, will only select the first match.

    My code loops over all elements that match, and for every one of those elements, it uses its own rel-tag to change its own src-tag, using this / $(this).