Reputation: 13
I would like to click on my image and have it disappear and move to the right in a different location. Currently, my image runs off the screen to the right. Please help me to create a code using the timeout()
that allows my image to hide and show.
php code
<div id= "ben" style= "position: relative; visibility: visible;" onclick="moveRight()" >
<img src = "images/ben.JPG" height = "250" width = "200" alt= "Picture of Peek-a-boo Ben"/>
//JavaScript for a hide/show image in different location
var ben = null;
var animate ;
function init(){
ben = document.getElementById('ben');
ben.style.position= 'relative';
ben.style.left = '0px';
}
function moveRight(){
ben.style.left = parseInt(ben.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
ben.style.left = '0px';
}
window.onload =init;
Upvotes: 1
Views: 2772
Reputation: 11749
I would definitely personally use jquery for this....
But if you want it in pure javascript, here it is....albeit the animation is done using CSS.
//JavaScript for a hide/show image in different location
var ben = null;
var animate=0 ;
function init(){
ben = document.getElementById('ben');
}
function toggled(){
var image = document.getElementById('image2');
if( animate==0){
animate = 1;
image.className= "right";}
else if(animate==1){
animate=0;
image.className= "left";}
}
window.onload =init;
DEMO HERE....just adjust the From and To in the CSS to move it further or closer
And the relevant CSS...
.right {
-webkit-transform: translateX(150px);
-webkit-animation-name: right;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1;
}
.left {
-webkit-transform: translateX(0px);
-webkit-animation-name: left;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1;
}
@-webkit-keyframes right { from { -webkit-transform: translateX(0px); }
to { -webkit-transform: translateX(150px); }}
@-webkit-keyframes left { from { -webkit-transform: translateX(150px); }
to { -webkit-transform: translateX(0px); }}
EDIT
This is it using JQuery...with no CSS Required.....All those lines of code above ^^ reduced to two.....gotta love Jquery :) It actually could get even simpler using the built in toggle() function to.......
var tog=0;
$('#ben').click(function(){
if(tog==0){$('#image2').animate({marginLeft: "250"}, 1500);tog=1; return false;}
else if(tog==1){$('#image2').animate({marginLeft: "0"}, 1500);tog=0; return false;
} });
(note... you have to include the Jquery library, and call $(document).ready(function(){ if you plan on using this code...
Also, you dont have to do onclick in your HTML anymore...
ie... <div onclick="moveRight()">
As Jquery's handling it for you, using click()
Upvotes: 1