Search code examples
jqueryfade

How do I use the jQuery script for multiple divisions?


I want the first pic to fade to the next pic on mouseenter and reverse on mouseleave. I want to use the jQuery script for multiple id's

<script type="text/javascript">
$('#picone1').mouseenter(function(){
   $('#picone1').fadeToggle(500);
   $('#pictwo1').fadeToggle(500);
});
$('#pictwo1').mouseleave(function(){
   $('#picone1').fadeToggle(500);
   $('#pictwo1').fadeToggle(500);
});
</script>
<div id="fade">
   <img src="two.gif" width="100" height="100" id="pictwo1" style="display:none;"/>
   <img src="one.gif" width="100" height="100" id="picone1"/>
</div>
<div id="fade">
   <img src="two.gif" width="100" height="100" id="pictwo2" style="display:none;top: 300px;" />
   <img src="one.gif" width="100" height="100" id="picone2" style="top: 300px;" />
</div>

if I use

$('#picone1,#picone2').mouseenter(function(){

how to fade only the div over which the mouse has entered?

Is there any other or better script to do this?


Solution

  • In jQuery inside of any event callback this refers to the DOM element that triggered the event. So if you do:

     $('#picone1, #picone2').mouseenter(function() {
         // $(this) refers to whichever div was entered, so you can do:
         $(this).fadeToggle(500);
         $(this).prev('img').fadeToggle(500); // get previous IMG in the DOM and fade
     });
    

    I would recommend if you are just doing this a lot to give the images classes instead of IDs, so you can just do something like $('img.before') and refer to the other img relatively.