Reputation: 15959
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#tempc {
background-color: #FFFF00;
width: 50px;
height: 50px;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggle(){
$("#tempc").toggle(
function () {
$("#tempc").animate({width: 255, height: 300}, 1000, "easeInOutQuad")
},
function () {
$("#tempc").animate({width: 50}, 1000, "easeInOutQuad")
}
);
}
</script>
</head>
<body>
<div id="tempc" onclick="toggle();">
Hello!
</div>
</body>
</html>
Hello Stackoverflow, I try to use toggle to switch in animate functions, but the code showen above doesn't seem to work? What is wrong?
Greetings
Upvotes: 0
Views: 918
Reputation: 2623
Try something like this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#tempc {
background-color: #FFFF00;
width: 50px;
height: 50px;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div id="tempc">
Hello!
</div>
<script type="text/javascript">
$().ready(function(){
$('#tempc').toggle(
function(){
$(this).animate({width: 255, height: 300}, 1000, 'linear')
},
function () {
$(this).animate({width: 50}, 1000, 'linear')
}
);
});
</script>
</body>
</html>
The onclick
handler has been removed from the div
because it's unnecessary when using jQuery.
Also, the instances of $('#tempc')
in the callbacks has been changed to $(this)
. This is the "correct" way of doing things and I believe this is more efficient for the Javascript engine (correct me if I'm wrong!).
Also, you were trying to use the "easeInOutQuad"
function as the easing function. According to the jQuery docs, the only built-in functions that are supported are swing
and linear
:
Easing: The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.
See the jQuery docs for more info: jQuery Animate()
Upvotes: 0
Reputation: 35344
Change this:
<body>
<div id="tempc" onclick="toggle();">
To this:
<body onload="toggle();">
<div id="tempc">
Upvotes: 1
Reputation: 11658
Setup toggle handler on pageload using jquery ready function. Remove onclick handler from div. Check this code.
$(function (){
$("#tempc").toggle(
function () {
$("#tempc").animate({width: 255, height: 300}, 1000);
},
function () {
$("#tempc").animate({width: 50}, 1000);
}
);
});
Upvotes: 1