-1

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.

Paul
  • 1,277
  • 5
  • 28
  • 56

3 Answers3

4

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)();
trincot
  • 317,000
  • 35
  • 244
  • 286
3

You still have to let the function know what the parameter is:

function findClass(self) {
    var classString = $(self).attr('class');
    var myClass = classString.split(' ')[0];
    alert(myClass);
}
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
0

Use call or apply function. Here is a slightly modified example that demonstrates how you can do this:

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

findClass.call({'class': "Hello World"})
findClass.apply({'class': "Hello World"})
randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72