tags:

views:

38

answers:

1

Hello, 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 mouse-over I want to add an image with opacity and make the project-title shown. So I use 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?

Thank you

+2  A: 

You can use one .hover() function for everything that's relative not ID dependent, like this:

$('.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 hovered instead of having a different function to handle each one...you could probably remove the IDs from your elements as well unless they serve another purpose. Since currently you have invalid HTML with the ID being used twice each time, this resolves that as well.

Nick Craver
Hi,the ".find" it does not work like this. Maybe is $(this).find??
novellino
Perfect!!! It works like this.Thank you very much!!
novellino
I think you need to remove the semicolons in the first line. The `closest` call is supposed to chain to the line before.
RoToRa
@RoToRa - Woops, thanks! fixed above.
Nick Craver
I added it to this $(this).closest....But yes if I delete the semicolon is better.Thanks again
novellino