Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate()

My code is as given below :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
#Layer1 {
 position:absolute;
 width:200px;
 height:115px;
 z-index:1;
 left: 445px;
 top: 64px;
}
-->
</style>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function toggle()

{

$("#Layer1").animate({width:"20px"},1000);

}
</script>
</head>

<body onload="toggle()">
<div id="Layer1"><img src="friend-line.jpg" width="243" height="380" /></div>
</body>
</html>

As the page loads, there is an animation, but soon enough, the dimensions of Layer 1 are restored. I'd like to know why this is happening.

like image 714
Anant Avatar asked Oct 02 '10 17:10

Anant


2 Answers

The animation adds the CSS of overflow:hidden while it's going. When it stops, the overflow goes back to its previous state, so you should simply permanently add the overflow:hidden CSS to #Layer1

Additionally, I suggest that you use the jQuery doc ready functionality instead of the inline onload Javascript.

So your entire JS would be:

$(function() { // <== doc ready
    $("#Layer1").css("overflow","hidden").animate({width:"20px"},1000);
});

jsFiddle example


I'm not quite sure as to what you're trying to accomplish with your code, but you could also include the overflow:hidden in you CSS for #Layer1:

#Layer1 {
 position:absolute;
 width:200px;
 height:115px;
 z-index:1;
 left: 445px;
 top: 64px;
 overflow:hidden;
}

With the above CSS you can use your original code, just wrap it in a doc ready and remove the onload from the HTML:

$(function() { // <== doc ready
    $("#Layer1").animate({width:"20px"},1000);
});

jsFiddle example

Note that the width of the div is smaller than the width of the image. Not sure if this is on purpose.

like image 79
Peter Ajtai Avatar answered Sep 21 '22 21:09

Peter Ajtai


its possibly because you are changing the div width and not the width of the img

also is best practice to use $(document).ready() on the script than using onload on body

if you do not wish to change the image size but just hide the reset of the contents on your css u can add overflow: hidden;

otherwise i cn't see why there should a problem.

like image 25
Val Avatar answered Sep 21 '22 21:09

Val