lesssugar
lesssugar

Reputation: 16181

Passing $(this) to jQuery .hover() functions

I wrote a simple tooltip functionality, to be seen here.

The thing is, in both handler functions set in .hover() I need access to $(this) and other 2 variables based on it. In order do achieve that, I declare the same 3 variables in both handlers:

$('a').hover(
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    },
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    }
);

DRY principle should be respected, so my question is: Is there other and smarter/less dirty way of passing the same variables set to both functions within .hover()?

Obvioulsy, the variables can't be global (and globals are evil anyway).

Any ideas how to achieve this with jQuery or pure JS?

Upvotes: 3

Views: 1394

Answers (1)

Blazemonger
Blazemonger

Reputation: 92963

Call one named function inside the anonymous callbacks:

$('a').hover(function() {
        hoverFunc($(this), true)
    }, function() {
        hoverFunc($(this), false)
    });

function hoverFunc($this, is_hovered) {
    var link_offset = $this.offset();
    var link_tooltip = $this.data('tooltip');
    if (is_hovered) {
        console.log('ok')
        // do something
    } else {
        console.log('out')
        // do something else 
    };
}

http://jsfiddle.net/mblase75/8njk2m32/

Upvotes: 6

Related Questions