jquery change background image on hover
11,057
What is the id?
Is it some mysterious variable defined somewhere else or do you think the id will be read from the selector is some magical way?
I am guessing you want to use each() to get the id.
Author by
circey
Updated on June 04, 2022Comments
-
circey almost 2 years
I have several divs that I want to generate css background images for. They will change on hover. Yes, I'm aware that I could easily do this in css, but it needs to be done in jquery.
Code:
$(document).ready(function() { $('.hoverBox').css('background', 'url(img/box' + id + '.jpg)') $('.hoverBox').hover(function(){ $(this).css('background', 'url(img/box' + this.id + '_back.jpg)') }, function(){ $(this).css('background', 'url(img/box' + this.id + '.jpg)') }); });
HTML is like this:
<div class="hoverBox" id="benefits"> content</div> <div class="hoverBox" id="installation"> content</div> <div class="hoverBox" id="shoponline"> content</div>
This should be so easy, but I can't seem to make it work.
Assistance would be much appreciated! TIA.
-
circey over 13 yearsGreat. Thanks for that - got it working. The sarcasm was unnecessary, but each() was what I needed.
-
ithil almost 11 yearsHow about updating your code or adding an example of how you used "each()" to solve the problem? It would be helpful to others (like me ^^) having the same problem.