MooTools Image MouseOvers – Cleaner JavaScript Code, Less Hassle

By  on  

Creating mouseover code can be a real mess but using MooTools I put together a solution that saves me time and keeps my code super clean. There are some practices that I use with my theory. All "mouseover" versions of the image end in "-mo". For example, sugar.jpg is the standard image while sugar-mo.jpg is the mouseover version. Also, I use a CSS class mo to identify which items have mouseovers. I also stick to one file extension and assume that the mouseover image's file extension is the same as the original file's extension.

The Code

window.addEvent('domready', function() {
$$('img.mo').each(function(img) {
	var src = img.getProperty('src');
	var extension = src.substring(src.lastIndexOf('.'),src.length)
	img.addEvent('mouseenter', function() { img.setProperty('src',src.replace(extension,'-mo' + extension)); });
	img.addEvent('mouseleave', function() { img.setProperty('src',src); });
});
});

The Usage

<a href="/"><img src="/graphics/sugar.jpg" alt="Sugar" class="mo" height="50" width="150" /></a>

That's it. Simply add the mo CSS class to the image and save yourself any ugly, bloated "onmouseover" code. Remember not to use the mo CSS class anywhere else!

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    iPhone Click Effect Using MooTools or jQuery

    One thing I love about love about Safari on the iPhone is that Safari provides a darkened background effect when you click a link. It's the most subtle of details but just enforces than an action is taking place. So why not implement that...

  • By
    GitHub-Style Sliding Links

    GitHub seems to change a lot but not really change at all, if that makes any sense; the updates come often but are always fairly small. I spotted one of the most recent updates on the pull request page. Links to long branch...

Discussion

  1. Hi,

    this works really well, thanks. How could I add a duration to make the transition smoother? Sorry, not too good with mootools yet!

    Best wishes,
    Jay

  2. Glad you like it Jay! You can view more information on MooTools transitions at the MooTools website:

    http://docs.mootools.net/Effects/Fx-Transitions.js

    I don’t know how much “smoother” you can make it, but feel free to create something of your own!

  3. I failed to achieve the result I was looking for using your code (although I know it’s possible) but came up with a solution which others might find helpful.

    Example: http://www.enableincornwall.co.uk/index.php

    Code:
    http://forum.mootools.net/viewtopic.php?pid=28886#p28886

  4. Does this preload the images also.

  5. I always having problem with mootools coz it always generate conflict to my website templete. especially working with CMS like Durpal or Joomla. Probably I need more study on mootools framework.

  6. The answer to my question is: no it does not pre-load images. But I was able to modify it to do so as well as to append the original image source with “-over” rather then read the mo property. I didn’t try to W3C validate the page with the mo property but my guess is it will not considering mo is not a valid entity. Thanks for the head start. I am new to mootools and other javascript frameworks but they are definitely time savers just like the php frameworks I use.

  7. Thanks for sharing this mouseover function! I will try it tonight and see how it works.

  8. smartwork

    It is working good, i just want to know can we do some kinda transition effect between each image. Do you have any idea David?
    You can check this site, but this is not a mootools
    http://www.alistapart.com/articles/sprites2#

  9. @smartwork: This wouldn’t be the solution you were looking for. That article is nice — I’m not aware of a MooTools alternative.

  10. smartwork

    No, No, i didn’t ask other than mootools, i want to do such kinda effects in mootools, for reference i had sent that url. oops something i confused you.

  11. Bigsimon

    With Preload

    window.addEvent('domready', function() {  
    
    $$('img.mo').each(function(img) { 
         var src = img.getProperty('src'); 
         var extension = src.substring(src.lastIndexOf('.'),src.length)  
    
         // Preload the image
         new Asset.images([src.replace(extension,'-over' + extension)]);
    
     img.addEvent('mouseenter', function() { img.setProperty('src',src.replace(extension,'-over' + extension)); });  
     img.addEvent('mouseleave', function() { img.setProperty('src',src); });  
    
    
    }); 
     }); 
  12. jeroen

    Are there any examples of the total result?
    Link doesn’t work ):

  13. @jeroen: Link updated.

  14. bill

    How can I add an onpage state…so that when I’m on a page, the image-op.png is used instead of image.png, but still on mouseover it uses image-mo.png

  15. Alex

    it’s messy but this works for an ‘onpage’ button, it’s basically the same function again that works slightly differently. It assumes the ‘on’ button is named xxxxx-on.png and you need to give that image the class ‘omo’:

    //rollover for current page button
        $$('img.omo').each(function(img) {
            var src = img.getProperty('src');
            var extension = src.substring(src.lastIndexOf('.'),src.length);
            var root = src.substring(0,src.lastIndexOf('-'));
            img.addEvent('mouseenter', function() { img.setProperty('src',root + '-mo' +extension); });
            img.addEvent('mouseleave', function() { img.setProperty('src',src); });
        });
    
  16. I was looking for a similar solution and found a few solutions through various forums using the Fx.Style constructor, however I thought why cant one just use the fade plugin to make this work with a div background of the final output, Heres the code:

    window.addEvent('domready',function() {    
    
    $$('.fade').each(function(el){
        el.addEvent('mouseenter', function() {
            el.getFirst().fade(0.01);   
        });
        el.addEvent('mouseleave', function() {
            el.getFirst().fade(1);
        });
    },this);
    
    });
    

    <div style="background:transparent url(yourimage-mo.jpg) no-repeat;">
    <p><a class="fade" href="#" title="" style="border:none;"><img

    style="border:none;"
    src="yourimage.jpg" alt="" />

    </div>

  17. Great stuff.
    You could also preload the images in the same function using Asset.images
    Here is the update code:

    window.addEvent('domready', function() {
    
    var images = [];
    
    $$('img.mo').each(function(img) {
        var src = img.getProperty('src');
        var extension = src.substring(src.lastIndexOf('.'),src.length)
        var srch = src.replace(extension,'-h' + extension);
        images.include(srch);
        img.addEvent('mouseenter', function() { img.setProperty('src',srch); });
        img.addEvent('mouseleave', function() { img.setProperty('src',src); });
    });
    
    var loader = new Asset.images(images);
    
    
    });
    

    That way, the “hover” image is automatically loaded at startup.
    Vedivi Dev Team

  18. Justin

    Great code, certainly makes life easy. Thanks David. Was wondering though… i’m changing the src of an image dynamically (think a play/pause button) using:

    document.getElementById('pauseButton').src = 'http://mydomain/images/pause_btn.gif';
    

    I’d like to use your mouseover script to affect both the play button AND the pause button (when the src changes). I haven’t been able to get it to work so far. Do you have any suggestions as to how I could get this to work?

    Cheers,
    Justin

  19. do you have a function like this for jQuery? I love using this when working with mootools…but a new project required jQuery be used. So now I have to find comparable “tools” or “convert” stuff to jQuery – which isn’t likely for me.

  20. Nevermind…found a jQuery scripts that is very close to yours…in case anyone else is looking for something like this too: http://peps.ca/blog/easy-image-rollover-script-with-jquery/

  21. Ravishankar

    THanks for the info… I hav e a qn…how did u make the image rollover on the banner of your website… its really cool. It would be great if you can send me the link for the tutorial or the code for it.Thanks in advance

  22. what’s the code required for duration to be added?

  23. Johnny

    Hey – i’m trying to find a link where i can see the final results. As you told jeroen a few years ago, you updated a Link – but i can’t find it anywhere. Am I just looking at the wrong place or was the demo removed? Please help me here!

  24. mitropas

    hi David,

    thank you very much for the script.
    All works fine, but i would like to include a smooth fading effect within the swap.
    Is it possible to modificate the script, and can you help me with that?

    thank you very much!

  25. Thanks! I’m looking for the effect which can change the small part of image contained in larger image. Can you provide me some information ? Thank you

  26. I have been here over the years and happily used some of your code. I one of those who need both the code and a ‘real working example’. Without it I will spent hours and often fail. So is there any example of this functionality on-line?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!