Ok, so I recently started learning jQuery, but I’m having trouble with a little animation program I got off of the jQuery website.
So here is the problem. This program works:
<HTML>
<HEAD>
<script type="text/javascript" src="javascript/jQuery-1.7.1.min.js"></script>
<STYLE type="text/css">
#content {
background-color:#6688ff;
position:absolute;
width:100px;
height:100px;
padding:3px;
margin-top:5px;
left: 100px;
}
</STYLE>
</HEAD>
<BODY>
<input type="button" id="left" value="Left"/>
<input type="button" id="right" value="Right"/>
<div id="content">Move</div>
<script type="text/javascript">
$("#right").click(function() {
$("#content").animate(
{"left": "+=50px"},
"slow");
});
$("#left").click(function() {
$("#content").animate(
{"left": "-=50px"},
"slow");
});
</script>
</BODY>
</HTML>
But this program doesn’t:
<HTML>
<HEAD>
<script type="text/javascript" src="javascript/jQuery-1.7.1.min.js"></script>
<script type="text/javascript">
$("#right").click(function() {
$("#content").animate(
{"left": "+=50px"},
"slow");
});
$("#left").click(function() {
$("#content").animate(
{"left": "-=50px"},
"slow");
});
</script>
<STYLE type="text/css">
#content {
background-color:#6688ff;
position:absolute;
width:100px;
height:100px;
padding:3px;
margin-top:5px;
left: 100px;
}
</STYLE>
</HEAD>
<BODY>
<input type="button" id="left" value="Left"/>
<input type="button" id="right" value="Right"/>
<div id="content">Move</div>
</BODY>
</HTML>
The only difference between the two programs is where I put the javscript, so could anyone explain me why that makes a difference? Thanks, cause that is confusing me.
The document isn’t ready when the second jQuery code chunk runs, so it doesn’t work.
Always wrap your jQuery code in a
$(document).ready()statement:Your second code chunk is correct.