Only just starting out with jQuery and I’m sure this is basic stuff for those that know, but I can’t get it working.
I have a very simple and repetitive script that I’m trying to streamline, that changes the background colour of a background div, when certain links are hovered. i.e. each link has an associated background div.
$('div#navigation a.A').hover(function(){
$('div#bg-nav .A').addClass('bg-active');
},function(){
$('div#bg-nav .A').removeClass('bg-active');
});;
$('div#navigation a.B').hover(function(){
$('div#bg-nav .B').addClass('bg-active');
},function(){
$('div#bg-nav .B').removeClass('bg-active');
});;
This is repeated for each link. Links and the background divs are created dynamically by the CMS so manually updating this script every time a page is added isn’t ideal. And I can’t use pure CSS because of where the links are in relation to the divs within the page structure.
As there is an obvious pattern, (the background divs have the same class as the trigger links), I figured it must be possible to use the class of the link being hovered to affect the relevant div, passing the variable onto the selectors, something like below, but as a newb I can’t get it working!
$(document).ready(function() {
var linkClass = $(this).attr("class");
$("div#navigation a").hover(function() {
$('div#bg-nav.'+ linkClass).addClass('bg-active');
},function(){
$('div#bg-nav.'+ linkClass).removeClass('bg-active');
});;
I think this should work. Also take a look at Density 21.5’s answer for details.