views:

67

answers:

2

What I'm doing is adding a class to all elements who have the same class name as the id I'm hovering over. For example when I hover some list item with the id of vowel, then all the span elements with the class of the name vowel get acted upon (adding a class).

I can do that with no problems. But I want to do the same thing for many other id names with corresponding class names. Examples: consonants, semi-vowels, gutturals, palatals, etc.

I could do all these with different functions but I want to do is to call a function which will perform the same tasks but will be smart enough to find the name of the id and to generate the class name from that.

How do I extract the id name into a variable and assign it to the class name.

+1  A: 

You could do this:

$("[id]").hover(function() {
  $("." + this.id).addClass("highlight");
}, function() {
  $("." + this.id).removeClass("highlight");
});

but I wouldn't necessarily recommend it. I'd be more inclined to statically define it:

var ids = ["vowels", "consonants"];
for (var i = 0; i < ids.length; i++) {
  $("#" + ids[i]).hover(function() {
    $("." + this.id).addClass("highlight");
  }, function() {
    $("." + this.id).removeClass("highlight");
  });
}

or something like that.

cletus
I almost works but the "." + ids[i] bit does not do anything. On line 3 of your code I have been testing this code and it works:$(this).css({'cursor' : 'default'});but for some reason, on the same line the following does not work:$("#" + ids[i]).css({'cursor' : 'default'});I hope this will give you a clue on how to help me further.
allesklar
line 3 of your second solution
allesklar
well i meant line 4 (FOUR) of your second code snippet.
allesklar
Thanks for your help cletus. I made it work by replacing ids[i] with $(this).attr('id') on line 4 and 6 of your second solution.
allesklar
+2  A: 

You could use a plugin:

$.fn.highlight = function() {
    return this.each(function() {
        $(this).hover(function() {
            var id = $(this).attr('id');
            $('.'+id).addClass('myclass');
        });
    });
}

Which you could call like this:

$(document).ready(function() {
    $('span').highlight();
});
Steerpike
Thank you Steerpike. I used some of your solution with some of cletus solution to make it work. Cheers.
allesklar