Need optimized code to hide and show div in jQuery

I have a div:

<div id="p1" class="img-projects" style="margin-left:0;">
  <a href="project1.php"> <img src="image1.png"/></a>
  <div id="p1" class="project-title">Bar Crawler</div>
</div>

      

On mouseover, I want to add an image with opacity and show the project name. So I am using this code:

<script type="text/javascript">
    $(function() {
        $('.project-title').hide();

            $('#p1.img-projects img').mouseover(
               function() {
                   $(this).stop().animate({ opacity: 0.3 }, 800);
                   $('#p1.project-title').fadeIn(500);
            });
            $('#p1.img-projects img').mouseout(
               function() {
                   $(this).stop().animate({ opacity: 1.0 }, 800);
                   $('#p1.project-title').fadeOut();
            });


            $('#p2.img-projects img').mouseover(
               function() {
                   $(this).stop().animate({ opacity: 0.3 }, 800);
                   $('#p2.project-title').fadeIn(500);
            });
            $('#p2.img-projects img').mouseout(
               function() {
                   $(this).stop().animate({ opacity: 1.0 }, 800);
                   $('#p2.project-title').fadeOut();
            });

    });

</script>

      

The code works fine, but does anyone know a way to optimize my code?

thanks

+2


a source to share


1 answer


You can use a function .hover()

for anything that is relative independent of the ID, for example:

$('.img-projects img').hover(function() {
   $(this).stop().animate({ opacity: 0.3 }, 800)
          .closest('.img-projects').find('.project-title').fadeIn(500);
}, function() {
   $(this).stop().animate({ opacity: 1.0 }, 800)
          .closest('.img-projects').find('.project-title').fadeOut();
});

      



This finds all elements relative to the one that was visible, instead of having a different function to handle each one ... you could probably remove ids from your elements if they don't serve a different purpose. Since you currently have invalid HTML with an ID used twice each time, this also fixes it.

+2


a source







All Articles