Sunday, June 3, 2012

Change the image source using jQuery


I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:




Original Image: Image.gif



Rollover Image: Imageover.gif




I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.



How can I do it using jQuery?


Source: Tips4all

13 comments:

  1. To set up on ready:

    $(function() {
    $("img")
    .mouseover(function() {
    var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
    $(this).attr("src", src);
    })
    .mouseout(function() {
    var src = $(this).attr("src").replace("over.gif", ".gif");
    $(this).attr("src", src);
    });
    });

    ReplyDelete
  2. I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:

    #element {
    width: 100px; /* width of image */
    height: 200px; /* height of image */
    background-image: url(/path/to/image.jpg);
    }

    #element:hover {
    background-image: url(/path/to/other_image.jpg);
    }


    There's a longer description here:http://tutorials.alsacreations.com/imgreactive/

    Even better, however, is to use sprites: http://www.findmotive.com/2006/10/31/simple-css-image-rollover/

    ReplyDelete
  3. /* Teaser image swap function */
    $('img.swap').hover(function () {
    this.src = '/images/signup_big_hover.png';
    }, function () {
    this.src = '/images/signup_big.png';
    });

    ReplyDelete
  4. $('img.over').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
    var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
    t.hover(function(){
    $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
    }, function(){
    $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
    });


    You may want to change the class of images from first line. If you need more image classes (or different path) you may use

    $('img.over, #container img, img.anotherOver').each(function(){


    and so on.

    It should work, I didn't test it :)

    ReplyDelete
  5. I was hoping for an über one liner like:

    $("img.screenshot").attr("src", $(this).replace("foo", "bar"));

    ReplyDelete
  6. If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A Sprites is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses a http-request, and the more http-request the more time it will take to load.

    .buttonClass
    {
    width:25px;
    height:25px;
    background:url(Sprite.gif) -40px -500px;
    }
    .buttonClass:hover
    {
    width:25px;
    height:25px;
    background:url(Sprite.gif) -40px -525px;
    }


    The 0px 0px coordinates will be the left upper corner from your sprites.

    But if you are developing some photo album with ajax or something like that, then javascript (or any framework) is the best.

    Have fun!

    ReplyDelete
  7. I wrote a small howto with examples for beginners here. There's also an example without using jQuery.

    ReplyDelete
  8. $('img').mouseover(function(){
    var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
    $(this).attr("src", newSrc);
    });
    $('img').mouseout(function(){
    var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
    $(this).attr("src", newSrc);
    });

    ReplyDelete
  9. If you have more than one image and you need something generic that doesn't depend on a naming convention.

    HTML

    <img data-other-src="big-zebra.jpg" src="small-cat.jpg">
    <img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
    <img data-other-src="friendly-bear.jpg" src="penguin.jpg">


    JavaScript

    $('img').bind('mouseenter mouseleave', function() {
    $(this).attr({
    src: $(this).attr('data-other-src')
    , 'data-other-src': $(this).attr('src')
    })
    });

    ReplyDelete
  10. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>JQuery</title>
    <script src="jquery.js" type="text/javascript"> </script>
    <style type="text/css">
    #box{
    width: 68px;
    height: 27px;
    background: url(images/home1.gif);
    cursor: pointer;
    }
    </style>

    <script type="text/javascript">

    $(function(){

    $('#box').hover( function(){
    $('#box').css('background', 'url(images/home2.gif)');

    });
    $('#box').mouseout( function(){
    $('#box').css('background', 'url(images/home1.gif)');

    });

    });
    </script>
    </head>

    <body>
    <div id="box" onclick="location.href='index.php';"></div>
    </body>
    </html>

    ReplyDelete
  11. Any reason why the code from Jarrod Dixon♦

    Doesn't work in IE 6 (except for the fact that it's IE 6)?
    I've tried this code and an "updated" version:

    $("img.imgNav").hover(function() {
    var src = $(this).attr("src").match(/[^\.]+/) + "over.png";
    $(this).attr("src", src);
    },
    function() {
    var src = $(this).attr("src").replace("over", "");
    $(this).attr("src", src);
    });


    The roll-over effect doesn't kick in. It works in FF and IE 7 but none seems to work in IE 6.
    Of course I added a fixed PNG solution for IE 6 (and other PNGs shows up correctly).

    ReplyDelete
  12. A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.

    HTML

    <img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


    JavaScript

    function swap(newImg){
    this.src = newImg;
    }


    Depending on your setup, maybe something like this would work better (and requires less HTML modification).

    HTML

    <img src="img1.jpg" id="ref1" />
    <img src="img3.jpg" id="ref2" />
    <img src="img5.jpg" id="ref3" />


    JavaScript / jQuery

    // Declare Arrays
    imgList = new Array();
    imgList["ref1"] = new Array();
    imgList["ref2"] = new Array();
    imgList["ref3"] = new Array();

    //Set values for each mouse state
    imgList["ref1"]["out"] = "img1.jpg";
    imgList["ref1"]["over"] = "img2.jpg";
    imgList["ref2"]["out"] = "img3.jpg";
    imgList["ref2"]["over"] = "img4.jpg";
    imgList["ref3"]["out"] = "img5.jpg";
    imgList["ref3"]["over"] = "img6.jpg";

    //Add the swapping functions
    $("img").mouseover(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
    }

    $("img").mouseout(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
    }

    ReplyDelete
  13. <img src="img1.jpg" data-swap="img2.jpg"/>



    img = {

    init: function() {
    $('img').on('mouseover', img.swap);
    $('img').on('mouseover', img.swap);
    },

    swap: function() {
    var tmp = $(this).data('swap');
    $(this).attr('data-swap', $(this).attr('src'));
    $(this).attr('str', tmp);
    }
    }

    img.init();

    ReplyDelete