Ahmad Fouad Ahmad Fouad - 1 year ago 73
jQuery Question

jQuery: Show a zoom button on hover over the image and another layer which is black but faded

I am trying to achieve simple effects here and there. Please look this code and tell me if I can achieve the same thing with a better approach.

I am trying to show a zoom button when I hover over the image and another layer which is black but faded to degree to get this common fade effect.

First that's my html sample:

<a href="<LARGE_IMAGE_URL" class="zoom(for fancybox)">
<img src="IMAGE_SMALL_SOURCE.jpg" />
<div class="zoom-overlay"></div>
<div class="zoom-black"></div>
</a>


This is the jQuery I wrote..

// click to zoom button
$(".zoom-overlay").css({display: "none"});
$(".zoom-black").css({display: "none"});
$(".slidingposts .image").hover(function(){
$(this).children("a").children(".zoom-black").show();
$(this).children("a").children(".zoom-black").fadeTo(1, 0.40);
$(this).children("a").children(".zoom-overlay").fadeIn(500);
},function(){
$(this).children("a").children(".zoom-black").hide();
$(this).children("a").children(".zoom-overlay").fadeOut(300);
});

$(".slidingposts .image").click(function(){
$(".zoom-black:visible").hide();
$(".zoom-overlay:visible").hide();
});


I do not know if I can achieve same results with better code. I feel it could be improved any guidance?

It seems to do what I want. First I want the black overlay to show then fade it a bit, then the main overlay with button appears (I styled that already) .. and whenmouse out i just hide the overlays and thats it.

I also put a code onclick to hide the visible overlays because it interfere with the fancybox wrap.

Any suggestions?

Answer Source

I'm not messing with your HTML, since I don't really know the details of the design there. Instead, I'm optimizing your jquery here. It's should be pretty much equivalent, just a little slimmer.

// click to zoom button
$(".zoom-overlay, .zoom-black").css({display: "none"});

$(".slidingposts .image a").hover(function(){
    $(this).children(".zoom-black").fadeTo(1, 400);
    $(this).children(".zoom-overlay").fadeIn(500);
},function(){
    $(this).children(".zoom-black").hide();
    $(this).children(".zoom-overlay").fadeOut(300);
});

$(".slidingposts .image").click(function(){
    $(".zoom-black:visible, .zoom-overlay:visible").hide();
});

I should explain a little. Since all the targets were the anchors, I added them to the end of the selector so all those children('a') could be removed. Then I consolidated some other selectors because you wanted to perform the same action on the targets.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download