JQuery selector: How to change the src attribute of an image tag when you hover over a link

I need to change the src attribute of the image when the link is over

<div class="clear span-33 last" id="navigation">
  <div class="hicon span-1"><a href="#" title="Homepage"><img src="../Assets/images/home.png" /></a></div>
</div>   

Also change it to the default when the link does not hang ...

+3
source share
5 answers

You really need to learn CSS sprites to switch the background on hover. But if you need to do this in jQuery, something like this should do it. Just change the source image to your liking (also preload the hover image):

var link = $('a'), 
    img  = link.children('img'), 
    orig = img.attr('src'), 
    over = 'over.png', 
    temp = new Image();

temp.src = over; // preloads

link.hover(function() {
    img.attr('src',over);
},function() {
    img.attr('src',orig);
}
+8
source

, , IMG ( rmbr jquery):

<script type="text/javascript">
$(document).ready(function(){

    $(".navbar li").each(function(){
        var link = $(this).children("a");
        var image = $(link).children("img");
        var imgsrc = $(image).attr("src");

        // add mouseover
        $(link).mouseover(function(){
            var on = imgsrc.replace(/.jpg$/gi,"_over.jpg");
            $(image).attr("src",on);
        });

        // add mouse out
        $(link).mouseout(function(){
            $(image).attr("src",imgsrc);
        });
    });

});
</script>



<ul class="navbar"><li><a href="#"><img src="/images/nav_home.jpg" alt="home" /></a></li>
    <li><a href="#"><img src="/images/nav_item2.jpg" alt="Item2" /></a></li>
    <li><a href="#"><img src="/images/nav_item3.jpg" alt="Item3" /></a></li>
     </ul>
+4
+1

.

$('a[title="Homepage"]').hover(
    function () {
        // this is the mouseon event
        $(this).children('img').attr('src', 'newimage.png');
    }, 
    function () {
        // this is the mouseout event
        $(this).children('img').attr('src', '../Assets/images/home.png');
    }
);
0

, , jQuery

                $('.hicon > a').hover(
                                  function(){
                                      $(this).html("<img src='../Assets/images/homeah.png' />");
                                      },
                                  function(){
                                      $(this).html("<img src='../Assets/images/home.png' />");
                                      }
                                  );

, .

0

Source: https://habr.com/ru/post/1727542/


All Articles