Reputation: 367
I want to be able to declare a function that I can use with any selector or method, therefore I thought it could be done like the following, but it does not work!
Why is that? :)
$(document).ready(function() {
$('img').hover(function(){
imageClass();
});
function imageClass() {
var thisClass = $(this).attr('class');
console.log(thisClass)
}
});
Upvotes: 1
Views: 114
Reputation: 145408
This, however, will also work:
$('img').hover(imageClass);
function imageClass() {
var thisClass = $(this).attr('class');
console.log(thisClass)
}
And one more option:
$('img').hover(imageClass);
function imageClass(e) {
var thisClass = $(e.target).attr('class');
console.log(thisClass)
}
Upvotes: 0
Reputation: 45124
You can try jQuery.proxy. It will allow you to pass this
If you are unable to figure out let me know.
Upvotes: 0
Reputation: 148120
You can pass $(this)
from hover event as an argument
, All you need is to change the imageClass method to receive a parameter
.
$(document).ready(function() {
$('img').hover(function(){
imageClass($(this));
});
function imageClass(obj) {
var thisClass = obj.attr('class');
console.log(thisClass)
}
});
Upvotes: 6