0

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.

2
  • I've got the feeling that this same effect can be greatly simplified using just CSS or only adding a class to the element that encapsulates these children. Please post your HTML code and structure so I can elaborate. Commented Nov 27, 2009 at 16:11
  • Thanks for looking into it but cletus solved it. I don't think HTML/CSS alone could have done it. Commented Nov 27, 2009 at 17:06

2 Answers 2

2

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Steerpike. I used some of your solution with some of cletus solution to make it work. Cheers.
1

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.

3 Comments

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.
line 3 of your second solution
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.