Ariyan
Ariyan

Reputation: 15138

use jquery hover from class method

I'm trying to use .hover method of jquery in a javascript class:

var test = {

    init:function(){
        $("#elm li").hover(test.showTitle(this), test.hideTitle());
    },
    showTitle:function(e){
        ...
    },
    hideTitle: function(){
        ...
    }

};

$(document).ready(function() {
    test.init();
});

but here this refers to class itself and not to eventObject.
How can I listen for events with jquery from a javascript class?

Upvotes: 0

Views: 45

Answers (3)

gpmcadam
gpmcadam

Reputation: 6560

If you simply remove the parenthesis and the usage of the this keyword, jQuery will call your functions with the required variables as expected within the context of the element.

var test = {

    init:function(){
        $("#elm li").hover(test.showTitle, test.hideTitle);
    },
    showTitle:function(e){
        console.log(e)
        console.log(this);
    },
    hideTitle: function(){
    }

};

$(document).ready(function() {
    test.init();
});

Upvotes: 2

Michael Dunlap
Michael Dunlap

Reputation: 4310

Wrap the call in an anonymous function that gives you access to e.

#("elm li").hover(function(e) {
    test.showTitle(e); //or this
}, function(e) {
   test.hideTitle(e); //or this
});

Upvotes: 1

krillgar
krillgar

Reputation: 12815

You should be applying that to each element that is returned by your class query.

$("#elm li").each(function() {
    var $self = $(this);

    $self.hover(test.showTitle($self), test.hideTitle());
}

Upvotes: 1

Related Questions