简体   繁体   中英

get element id for animate jQuery

I have a sprite image than when mouseenter/mouseleave occurs over it, the background position changes.This is working so far although there is probably a more efficient way of doing it. However I have several images I need to do this with and am trying to find a way to feed the id of the image into the jQuery rather than duplicate code.
The HTML:

<div class='featSmallBox' id='featSmallImg2'>
</div>

The image source is placed using CSS.
This is what I have so far for the jQuery.

 $("#featSmallImg2").mouseenter(function(){
                    $(this).animate({
                   backgroundPositionX:"100%"
                     });
                   });

 $("#featSmallImg2").mouseleave(function(){
                    $(this).animate({
                   backgroundPositionX:"0%"
                     });
                    });

Ideally I need to feed in the id of what is being mouseentered dynamically, but everything I've tried doesn't seem to work.
Apologies if this makes little to no sense. I'm new to both jQuery and this site.

If the jQuery code is the same for all divs containing the sprites, try changing $("#featSmallImg2") in your jQuery to $(".featSmallBox") . This way, all your divs with the class .featSmallBox will have this feature.

Check with event.target

$( "body" ).mouseenter(function( event ) {
   console.log( "mouseentered id: " + event.target.id);
});
$("div[id^='featSmallImg']").mouseenter(function(){
                    $(this).animate({
                   backgroundPositionX:"100%"
                     });
                   });

$("div[id^='featSmallImg']").mouseleave(function(){
                    $(this).animate({
                   backgroundPositionX:"0%"
                     });
                    });

Try this code. Event will be called for all div's whose id starts with 'featSmallImg'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM