Implement jQuery’s hover() Method in MooTools

By  on  

jQuery offers a quick event shortcut method called hover that accepts two functions that represent mouseover and mouseout actions. Here's how to implement that for MooTools Elements.

The MooTools JavaScript

/* hover! */
Element.implement({
	'hover': function(fn1,fn2) {
		return this.addEvents({
			'mouseenter': function(e) {
				fn1.attempt(e,this);
			},
			'mouseleave': function(e) {
				fn2.attempt(e,this);
			}
		})
	}
});

We implement hover() which accepts to functions; one will be called on mouseenter and the other on the mouseleave event. Each function is passed the corresponding event.

The Usage

/* fade in and out on hover event */
$('hover-me').hover(function(e) {
	this.fade('out');
}, function(e) {
	this.fade('in');
});

This simple example usage makes use of element fading.

Recent Features

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • By
    Link Nudging Using Dojo

    In the past we've tinkered with link nudging with MooTools and link nudging with jQuery. In an effort to familiarize myself with other JavaScript frameworks, we're going to try to duplicate that effect with another awesome framework: Dojo. The JavaScript: Attempt...

  • By
    MooTools Window Object Dumping

    Ever want to see all of the information stored within the window property of your browser? Here's your chance. The XHTML We need a wrapper DIV that we'll consider a console. The CSS I like making this look like a command-line console. The MooTools JavaScript Depending on what you have loaded...

Discussion

  1. Sorry Bro, but this is completely useless. There is no need for a “hover”-method with a sloppy API like jQuery has (there is clearly no point in “argument one is hover event and argument two is the mouseout event”).

    After all, the mootools approach isn’t really significantly more to write but it gives you more flexibility and more meaningful code:

    el.addEvents({
      mouseenter: fn,
      mouseleave: fn2
    });
    

    Also, by doing it the “mootoolsian”-way you can remove the events if you want or need to by doing el.removeEvent('mouseenter', fn).

  2. @Chris

    I like this, but after reading your reply I do agree with you. The reason why I like it is that it shows how flexible MooTools is — There is [almost] nothing that MooTools cannot do that other libs can. The thing that makes hover() less MooTools and more jQuery is the autobinding.

    Great post though.

  3. MooTools automatically binds every function to the element unless the function is bound already.

    Consider this example:

    var fn = function(){ console.log(this); };
    el.addEvent('click', fn);
    el.addEvent('click', fn.bind(someOtherElement));
    

    The first example will log the element and the second one will be bound to “someOtherElement”. We have it all!

  4. I see your point guys — I created this because it simply gives the dev a shorter way to accomplish something. It may also help jQuery users who are moving to Moo by making things a little bit more simple.

  5. Chris, that would be true if David’s code was written as it were in your first post, but the function with the action is enclosed inside of the anonymous (already bound) function.

  6. Damn Lim, I had forgotten about Mooj. You need to do a series of articles on that thing.

  7. Corey

    Chris, you can do the same in jQuery also, you don’t have to use hover().

    el.mouseover(fn).mouseout(fn2);
  8. As an exercise in demonstrating how easy it is to add your own syntax to MooTools, I think this post is totally fine and appropriate. None of us would ever do this for all the reasons pointed out in the comments above.

    My only comment is that it should return this for chaining:

    Element.implement({
        'hover': function(fn1,fn2) {
            return this.addEvents({
                'mouseenter': function(e) {
                    fn1.attempt(e,this);
                },
                'mouseleave': function(e) {
                    fn2.attempt(e,this);
                }
            })
        }
    });
    
  9. So I have to throw in my $0.02US —

    I implement this for Dojo based on the same “wow, why do people get so excited about an API that already exists” … but I changed the .hover() API some:

    hover: function(over, out){
         return this.onmouseenter(over).onmouseleave(out || over);
    }
    

    allowing you to do one function for both states:

    dojo.query(".blah").hover(function(e){ 
      // is e.type mouseover or mouseleave ? decide
    });
    

    Though I put it in my “mini lib” plugd:

    http://code.google.com/p/plugd/

    I even submitted a patch to jquery because I think the single function use makes sense and is even more ‘rockstar’ than two inline functions:

    http://dev.jquery.com/ticket/3498

    Regards,
    Peter Higgins

  10. It has potential! Got some idea, will share when finnished.

  11. Hello. I’am looking for this jQuery-Function in Mootools. Any Idea?

    $(document).ready(function() {
    
    $(".commentBox").hover(
      function() { $(this).find(".commentDate").css({'display' : 'inline'}); },
      function() { $(this).find(".commentDate").css({'display' : 'none'}); }
    );
    });
    
  12. @joe This should do what you ask:

    window.addEvent('domready', function(){
        $(document.body).getElements('.commentBox').addEvents({
            'mouseenter': function(){
                this.getElement('.commentDate').setStyle('display','inline');
            },
            'mouseleave': function(){
                this.getElement('.commentDate').setStyle('display','none');
            }
        }) 
    });
  13. lossendae

    @Constantin:

    Which can be backported to jQuery

    $('document').ready(function(){
    $('.commentBox').bind('mouseenter mouseleave',function(){
    $(this).find('.commentDate').css({‘display’ : ‘inline’});
    },'mouseleave',function(){
    $(this).find('.commentDate').css({‘display’ : ‘none’});
    })
    });
    

    It’s not because jQuery has shortcuts that you must use them.

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