Paul Paul - 23 days ago 9
Javascript Question

Trying to pass "this" as an argument

I am trying to find out the class of an element when hovered over, and I am getting a

TypeError: undefined is not an object (evaluating 'classString.split')


console error. Here is my code.

function findClass(){
var classString = $(this).attr('class');
var myClass = classString.split(' ')[0];
alert(myClass);
}

//blog

$(".img2.blog").mouseenter(function() {
$('.img2.blog').css('opacity', '0');
$('.img1.blog').removeClass('hidden');

findClass(this);

});

//albums

$(".img2.albums").mouseenter(function() {
$('.img2.albums').css('opacity', '0');
$('.img1.albums').removeClass('hidden');

findClass(this);
});

//videos

$(".img2.videos").mouseenter(function() {
$('.img2.videos').css('opacity', '0');
$('.img1.videos').removeClass('hidden');

findClass(this);
});

//contact

$(".img2.contact").mouseenter(function() {
$('.img2.contact').css('opacity', '0');
$('.img1.contact').removeClass('hidden');

findClass(this);
});


Not sure how to pass "this" as an argument. Any help appreciated.

Answer

You can pass this, by using the call method:

findClass.call(this);

Someone will soon say it also works with apply. They only differ in how to pass the real arguments to the function (in case that were needed).

Check out the documentation on the two.

And to add one other method of the same family, with bind you can also achieve it:

findClass.bind(this)();