Reputation: 3
I have multiple elements on a page that have matching classes. The classes are built by a variable so I can't hard code the css into a stylesheet. The elements that make up the page will constantly change and so I need some javascript to find the element's class and then apply some css for that class. It's on a site with Jquery, Drupal (views) if that helps at all...
I'm part of the way there. I've written the following script:
$(document).ready(function(){
$("a").hover(function() {
var myClass = $(this).attr("class");
$(.$myClass).hover(function(){
$(this).css({
border : '3px solid red',
color : 'red'
});
});
});
});
Now if I put in there an 'alert', I see that it is capturing the class of the element that is currently being hovered over. But I can't get it to then find all of the elements on the page with that class and apply the css. To add some info, the two elements that I am trying to adjust are a small thumbnail image which I would like to add a border around, and the title of a linked node which I would like to change color.
Any help is much appreciated.
Upvotes: 0
Views: 1048
Reputation: 253496
The problem you're having is two-fold (at least), but effectively you're declaring the variable:
var myClass = $(this).attr("class");
And then trying to access that variable with a different name, .$myClass
, when it should be:
$(.myClass)
Also, the period for the selector is not part of the variable name, it's a string, and as such must be quoted and concatenated:
$('.' + myClass)
Further, you're not assigning behaviour to those other elements on hover of those elements, but on hover of the a
element you're currently hovering. So your
$("a").hover(function() {
var myClass = $(this).attr("class");
$(.$myClass).hover(function(){
$(this).css({
border : '3px solid red',
color : 'red'
});
});
Should be:
$("a").hover(function() {
var myClass = $(this).attr("class");
$('.' + myClass).css({
border : '3px solid red',
color : 'red'
});
});
Upvotes: 2