Search code examples
jqueryhtmlimagemousehover

Change src with jquery


I'm triyng to change the src of an image when i hover it ,but change it back when i no longer hover it.My problem is even if i ask just for the image with the src="img/fb-logo.png" it changes all the images when i hover over them and didnt change them back when i no longer hover. My code looks like this : HTML:

<footer>
    <div id="social-img">
        <a href=""><img src="img/fb-logo.png" alt="Sartoria Dana Design Facebook Page" /></a>
        <a href=""><img src="img/instagram-logo.png" alt="Sartoria Dana Design Instagram Page" /></a>
        <a href=""><img src="img/twitter-logo.png" alt="Sartoria Dana Design Twitter Page" /></a>
        <a href=""><img src="img/gplus-logo.png" alt="Sartoria Dana Design Google Plus Page" /></a>                            <a href=""><img src="img/yt-logo.png" alt="Sartoria Dana Design Youtube Channel" /></a>
    </div>
</div>
</footer>

Jquery:

$('footer #social img').mouseover(function () {
    if (this.src = "img/fb-logo.png") {
        this.src = "img/fb-logo-change.png";
    }
});

Solution

  • You can make it with a simple dataset. You must define all data what you need, in this case we can use data-hover and data-out and then manage it with jquery. Try this (run code snippet to see it working):

        $('img').on('mouseover',function () {
            var data = $(this).attr('data-hover');
            $(this).attr("src", data); // data-hover
        })
        $('img').on('mouseout', function() {
            var data = $(this).attr('data-out');
            $(this).attr("src", data); // data-out
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <img src="http://dummyimage.com/100x100/000000/ffffff&text=Image+1" 
           data-hover="http://dummyimage.com/100x100/ffffff/000000&text=Image+2"
           data-out="http://dummyimage.com/100x100/000000/ffffff&text=Image+1" />