I was playing around with the code from the w3schools editor which illustrates a jQuery animate function.
I want to try and make this movement reversible though, so I added an if/else statement to allow the div to move back if it had already been clicked.
Here is my code for between the script tags:
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = true;
} else {
$("div").animate({
right: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = false;
}
});
});
I am aware there is probably a better way of doing this, but I am fairly new to jQuery. In any case seeing as jQuery is just extended JavaScript it seems strange that this doesn't work.
--- update: corrected amount not being set and included full page code ---
Here is my new code. The div still doesn't move back when clicked again.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: '250px'
});
clicked = true;
} else {
$("div").animate({
right: '250px'
});
clicked = false;
}
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
leftandrightdon't cancel each other, to make it go back you have to setleft: 0