Reputation: 41
Just starting out with jQuery. I've ended up with some ugly code here to dynamically change the background on various regions of a world map. I'm constructing the same selector twice for the mouseover
and mouseout
. (That's what the hover
does: combine the two... yes?) Is there a cleaner way to do this? That is, only build it once and be able to use for both?
$('.regionName').hover(
function() {
var id = $(this).attr("id");
id = (id.substring(0, 2));
var region = "#" + id + "BG";
$(region).css('background', 'url(images/world-map-' + id + '.png) no-repeat');
},
function() {
var id = $(this).attr("id");
id = (id.substring(0, 2));
var region = "#" + id + "BG";
$(region).css('background', 'none');
}
);
Upvotes: 2
Views: 614
Reputation: 4010
Rather than making compact code, I prefer readability:
$('.regionName').hover(
function() {
var id = $(this).attr("id");
regionHelper(id);
});
//performs the toggle
function regionHelper(id){
id = id.substring(0, 2);
var region = "#" + id + "BG";
var element = $('#' + id);
if (element.css('background').length == 0){
element.css('background', 'url(images/world-map-' + id + '.png) no-repeat');
} else {
element.css('background', '');
}
}
Upvotes: 0
Reputation: 318272
$('.regionName').on('mouseenter mouseleave', function(e) {
var id = this.id.substring(0, 2);
$("#" + id + "BG").css('background', e.type==='mouseenter'?'url(images/world-map-' + id + '.png) no-repeat':'none');
});
From the jQuery docs:
Calling $(selector).hover(handlerIn, handlerOut) is shorthand for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Upvotes: 1
Reputation: 92943
Instead of that .css
method, create a custom class and use .toggleClass()
. You can then combine both of your functions into one:
$('.regionName').hover(
function() {
var id = $(this).attr("id");
id = (id.substring(0, 2));
var region = "#" + id + "BG";
$(region).toggleClass('addbg-'+id); // add on mouseover, remove on mouseout
}
);
Now add all the relevant .addbg-<whatever>
classes to your stylesheet, and you're good to go.
Upvotes: 0