Issue
I am trying to make a zoom-like effect on hover event in a gallery exercise. What I need is for an image to seem to expand from its center, not down and right. If I understood correctly, I need to move it half way left and up for this to work. Also, I'm using em
, so I try to convert em
to pixels here.
Relevant html:
<div id="gallery">
<img src="img/cool1.gif">
<img src="img/cool2.gif" id="gal2">
<img src="img/cool3.gif" id="gal3">
</div>
CSS:
#gallery {
width: 31em;
margin-left: auto;
margin-right: auto;
}
#gallery img {
width: 10em;
height: auto;
position: absolute;
}
#gal2 {
margin-left: 10em;
}
#gal3 {
margin-left: 20em;
}
Finally, jQuery:
var fontSize = $("#gallery img").css("font-size");//equal to 1em?
var fontInt = parseInt(fontSize);
var t = $("#gallery img").position().top;
var tNew = t - (5 * fontInt);//top position
var l = $("#gallery img").position().left;
var lNew = l - (5 * fontInt);//left position
$("#gallery img").hover(
function() {
$(this).stop().css("zIndex", "1").animate({
height : "20em",
width : "20em",
top : tNew,
left : lNew
}, 400);
}, //end mouseover
function() {
$(this).stop().animate({
height : "10em",
width : "10em",
top : t,
left : l,
zIndex : "0"
}, 400);
} //end mouseout
);//end hover
edit 1 Images expand and change position, but not as expected. Also, they don't return on mouseout. Thanks to Racil Hilan for solving em-px conversion problem!
edit 2 Problem moslty solved by fixing variable scope – position values moved before hover() function. The only remaining bug is that the pictures escape to the top right corner of the body before returning to their place on first interaction. Afterwards, it runs as expected. Also, could somebody explain why this works when the fontInt variable is multiplied by five, not by 10?
edit 3 – solution As Mauricio Santamaria said below, just add the css() function setting top and left parameters before hover on #gallery img element like so:
$("#gallery img").css({"top" : t, "left" : l}).hover(...);
The rest stays the same.
I improvised a fiddle for this, too: http://jsfiddle.net/dzenesiz/wudw5hmu/15/
Solution
The problem is that the $(this).css("font-size");
returns the size with the unit (e.g. 16px) which is not a number and the calculation results in a NaN
.
A quick solution is to parse it to an integer like this:
var fontSize = parseInt($(this).css("font-size")); //equal to 1em?
Answered By - Racil Hilan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.