How to move/slide an image from left to right - javascript

I want to slide or move a image from left to right something like in
http://rajeevkumarsingh.wix.com/pramtechnology
The read pentagonal box that moves Ok!
I tried a bit but failed to do so.
I used the code as below:
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
if (parseInt(imgObj.style.left)<=10)
{
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
}
else
stop();
f();
}
function stop(){
clearTimeout(animate);
}
window.onload =init;
//-->
</script>
<img id="myImage" src="xyz.gif" style="margin-left:170px;" />
There some kind of resolution problem with Firefox and IE as well. How to solve them. Also I am not able to move the things so clearly. Is this possible or not? I want it to be with JavaScript and not Flash.

var animate, left=0, imgObj=null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
left = parseInt(imgObj.style.left, 10);
if (10 >= left) {
imgObj.style.left = (left + 5) + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
} else {
stop();
}
//f();
}
function stop(){
clearTimeout(animate);
}
window.onload = function() {init();};

Here is an example of moving an image to the right as well as fading in from a .js file instead of your index page directly:
----------My index.html page----------
<!DOCTYPE html>
<html>
<body>
<script src="myJava.js"></script>
<script language="javascript" type="text/javascript">
//In pixels
var amountToMoveTotal = 1000;
var amountToMovePerStep = 10;
//In milliseconds
var timeToWaitBeforeNextIncrement = 20;
var amountToFadeTotal = 1.0;
var amountToFadePerStep = 0.01;
</script>
<p>This one moves right on hover</p>
<img onmouseover="moveRight(this, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:50px;position:absolute;opacity:1.0;">
<br><br>
<p>This one fades in on hover</p>
<img onmouseover="fadeIn(this, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:150px;position:absolute;opacity:0.1;">
</body>
</html>
----------My myJava.js code----------
var animate;
var original = null;
function moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original image location
if (original === null){
original = parseInt(imgObj.style.left);
}
//Check if the image has moved the distance requested
//If the image has not moved requested distance continue moving.
if (parseInt(imgObj.style.left) < amountToMoveTotal) {
imgObj.style.left = (parseInt(imgObj.style.left) + amountToMovePerStep) + 'px';
animate = setTimeout(function(){moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.left = original;
original = null;
clearTimeout(animate);
}
}
function fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original opacity
if (original === null){
original = parseFloat(imgObj.style.opacity);
}
//Check if the image has faded the amount requested
//If the image has not faded requested amount continue fading.
if (parseFloat(imgObj.style.opacity) < amountToFadeTotal) {
imgObj.style.opacity = (parseFloat(imgObj.style.opacity) + amountToFadePerStep);
animate = setTimeout(function(){fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.opacity = original;
original = null;
clearTimeout(animate);
}
}

Use the jQuery library, is really easy to do what you need
http://api.jquery.com/animate/
Follow sample code of page : http://api.jquery.com/stop/
<!DOCTYPE html>
<html>
<head>
<style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
<script>
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
</script>
</body>
</html>

Related

Change cursor image (CSS URL) using Javascript

I'm currently updating my website. I wanted to have an animated cursor on one of the pages. I found out that modern browsers don't support the .ani format or animated gifs, so I had the idea that I could use the .ani format for older browsers, and for modern browsers have a .png cursor that changes using javascript.
Here's what I tried:
<!DOCTYPE html>
<html>
<head>
<body background="example.gif">
<style type="text/css" id="cursor"> body {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;} </style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("cursor") .body images[x];
}
function startTimer() {
setInterval(displayNextImage, 400);
}
var images = [], x = -1;
images[0] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum1.png'), default;};
images[1] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum2.png'), default;};
images[2] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;};
</script>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("test") .src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 400);
}
var images = [], x = -1;
images[0] = "assets/shared/cursors/drum1.png";
images[1] = "assets/shared/cursors/drum2.png";
images[2] = "assets/shared/cursors/drum3.png";
</script>
</head>
<body onload="startTimer()">
<img id=test src="assets/shared/cursors/drum3.png">
<div style="height: 1000px; width: 1000px;"></div>
</body>
</html>
I put the 'test' image in to see if the code worked at all, and sure enough the 'test' image does change as planned, but the cursor just stays at 'drum3.png', not changing. I've tried it many different ways, but can't get it to work.
If possible I'd like to avoid JQuery.
Any help is really appreciated. Thank you!
You can use something like this:
var images = [
'http://lorempixel.com/21/21/',
'http://lorempixel.com/22/22/',
'http://lorempixel.com/23/23/'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 400);
html, body {
height: 100%;
}
body {
cursor: url('http://lorempixel.com/20/20/'), default;
}
I couldn't work out how to also have a .ani fallback cursor, so instead I changed my .png files to .cur files, which work in old and new browsers. So, the code ended up looking like this:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
var images = [
'assets/shared/cursors/drum1.cur',
'assets/shared/cursors/drum2.cur',
'assets/shared/cursors/drum3.cur',
'assets/shared/cursors/drum4.cur'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 250);
</script>
<body>
<div style="height: 1000vh; width: 1000vw;"></div>
</body>
</html>
</head>
</html>
Thank you again Shiva. I couldn't have worked this out without you.
I've asked a related, but different question here: Changing CSS URL for pointer cursor (using Javascript)

Javascript - Animation only working the first time the button is pressed

I have an animation which is called using onmousedown. I have another function which stops the animation (onmouseup).
The problem is that it only works the first time. By that I mean when I hold the button, it works and then stops when I stop pressing down but if I try to use either of the buttons after that first time nothing happens. It just won't move.
This is my HTML code (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
</html>
<script type='text/javascript' src='move.js'></script>
This is my javascript code (move.js):
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = document.getElementById("player").style.left;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = document.getElementById("player").style.left;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
Probably not important but here is my css (style.css):
body {
width: 100%;
height: 100%;
position:relative;
margin:0;
overflow:hidden;
}
#player {
position: absolute;
left:0;
bottom:0;
}
.buttons {
position:absolute;
right:0;
bottom:0;
}
Thanks for any help in advance.
You're running into 2 issues.
When you first get posl and posr, you're getting an empty string that JS is coercing to 0.
The -- and ++ won't work after you append the px (thus making posl and posr into string values)
Your posl-- (and posr++) can increment that coerced 0. That's why it works the first time through. The next time you mousedown the document.getElementById("player").style.left is a string — like "-1px" — that isn't interpreted as falsy (won't be coerced into 0). You can get around that by using parseInt() when you cache posl|posr but you have to provide a fallback of 0 because parseInt("") returns NaN…
You can work around that like so (with similar changes when you get posr):
var posl = parseInt( document.getElementById("player").style.left, 10 ) || 0;
var elem = document.getElementById("player");
function OnButtonDownl(button) {
//var posl = document.getElementById("player").style.left;
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}
}
function OnButtonUpl(button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr(button) {
//var posr = document.getElementById("player").style.left;
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}
}
function OnButtonUpr(button) {
clearInterval(idr);
}
body {
width: 100vw;// changed for example only
height: 100vh;// changed for example only
position: relative;
margin: 0;
overflow: hidden;
}
#player {
position: absolute;
left: 0;
bottom: 0;
}
.buttons {
position: absolute;
right: 0;
bottom: 0;
}
<img id='player' src='//placekitten.com/102/102' />
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)">Left</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">Right</button>
</div>
I was rewrite your code and it work (for me).
function Move(elem){
this.interval;
var posr = parseInt(getComputedStyle(document.getElementById("player")).left);
this.handleEvent = function(event) {
switch (event.type) {
case 'mousedown':
this.interval = setInterval(function() {
if (event.target.id == 'moveright') {
posr++;
} else if (event.target.id == 'moveleft'){
posr--;
}
document.getElementById("player").style.left = posr + 'px';
},5);
break;
case 'mouseup':
clearInterval(this.interval);
break;
}
}
elem.addEventListener('mousedown', this, false);
elem.addEventListener('mouseup', this, false);
}
var button_right = document.getElementById("moveright");
var button_left = document.getElementById("moveleft");
Move(button_right);
Move(button_left);
And in html you can remove js event listeners (this need only id).
First of all it is good practice to put your script tag inside your html tags:
<html>
<head>...</head>
<body>...</body>
<script type='text/javascript' src='move.js'></script>
</html>
Done that check this solution:
HTML:
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='https://placeimg.com/54/45/any' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDown('left')" onmouseup="OnButtonUp()"><--</button>
<button id='moveright' onmousedown="OnButtonDown('right')" onmouseup="OnButtonUp()">--></button>
</div>
<script type='text/javascript' src='move.js'></script>
</body>
</html>
And js:
var nIntervId;
var b;
var elem = document.getElementById("player");
var posl = document.getElementById("player").style.left;
function OnButtonDown(button) {
b = button;
nIntervId = setInterval(frame, 5);
}
function frame() {
if(b==='left'){
posl--;
elem.style.left = posl + 'px';}
else{
posl++;
elem.style.left = posl + 'px';
}
}
function OnButtonUp() {
clearInterval(nIntervId);
}
http://output.jsbin.com/varaseheru/

Using on click vanilla JS, activating on wrong node

Almost finished this sort of game i am working on to learn Dom manipulation. Basically the game spawns 5 images on the left and 4 on the right, you click the odd one out and then 10 spawn on the left and 9 on the right(+5 everytime).
I am wanting my nextlevel function to work every time the last child(of theLeftSide) is clicked on. It works the first time but after that regardless of if i click the correct node or not, my gameOver function is called and im not sure why. I tried removing the game over function and still the 2nd time i want my nextLevel to run(after click), it doesnt. Am i going about this the totally wrong way? Any input is appreciated thank you. Left my gameOver function in so you can see what im trying to do with it.
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h1> Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
<script src="script3.js"></script>
</body>
</html>
You just need to move the onclick inside the makeFaces after the while, so its added everytime after it creates them all:-
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h1> Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
<script src="script3.js"></script>
</body>
</html>

javascript slideshow without jquery

I cant find an example of what I am looking for -
I need a javascript slideshow that works WITHOUT jquery.
What the slideshow needs to do is display images, one by one (it would be nice if there would be a fading animation), and each image would be a link to another page. It is important that jquery is not used, because I am having some problems with that. I dont want any controls such as pause next... or any captions. Just <a> <img/> </a>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>JavaScript Fade - Brugbart Example</title>
<style type="text/css">
#Slideshow {
opacity: 1.0; /* CSS3 */
-moz-opacity: 1.0; /* Older versions of Firefox */
-khtml-opacity: 1.0; /* Older versions of Safari */
filter: alpha(opacity=100); /* Internet Explorer */
}
#Slideshow div {display:none;}
#Slideshow #slice1 {display:block;}
div{font-family: arial, sans-serif}
div{font-size:50px}
</style>
</head>
<body>
<div id="Basement" style="width:90%;margin:auto;">
<div id="Slideshow">
<div id="slice1">111111
</div>
<div id="slice2">222222
</div>
<div id="slice3">333333
</div>
</div>
</div>
<script type="text/javascript">
/* Creted with a reference from http://brugbart.com/slideshow-fade-javascript */
var duration = 250; /* fade duration in millisecond */
var hiddentime = 250; /* time to stay hidden */
var showtime = 1000; /* time to stay visible */
var active = 0 /* Used to check if fade is active */
var iEcount = 0 /* Element Counter */
var element = document.getElementById("Slideshow");
var iEarray = element.getElementsByTagName('div');
var iEtotal = iEarray.length;
StartFade();
function StartFade()
{
iEcount = 1;
setTimeout("FadeOut()", showtime);
}
function FadeOut()
{
for (i = 0; i <= 1; i += 0.01)
{
setTimeout("SetOpa(" + (1 - i) +")", i * duration);
}
setTimeout("FadeIn()", (duration + hiddentime));
}
function FadeIn()
{
for (i = 0; i <= 1; i += 0.01)
{
setTimeout("SetOpa(" + i +")", i * duration);
}
if (iEcount == iEtotal)
{
iEcount = 1
document.getElementById("slice" + iEcount).style.display = "block";
document.getElementById("slice" + iEtotal).style.display = "none";
}
else
{
document.getElementById("slice" + (iEcount + 1)).style.display = "block";
document.getElementById("slice" + iEcount).style.display = "none";
iEcount = iEcount+1
}
setTimeout("FadeOut()", (duration + showtime));
}
function SetOpa(Opa)
{
element.style.opacity = Opa;
element.style.MozOpacity = Opa;
element.style.KhtmlOpacity = Opa;
element.style.WebkitOpacity = Opa;
element.style.KhtmlOpacity = Opa;
element.style.MsOpacity = Opa;
element.style.width = "500px";
element.style.filter = 'alpha(opacity=' + (Opa * 100) + ');';
}
</script>
I would look at the answers here posted May 25, 2012. Similar questions have been asked many times. It helps to search for answers that have been already answered.
I have currently implemented just what you are trying to do. Very similar to what is in the post I linked to.

Javascript - Move an image to the right

This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left);
var tim = setTimeout("moveRight(id, speed)",50);
right = right+speed; // move
if (right > window.screen.height / 2)
{
right=0;
pp.style.left = right+"px";
}
}
</script>
Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.
<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;"> </div>
<script type="text/javascript">
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left) || 0;
right += speed; // move
pp.style.left = right + "px";
var move = setTimeout(function() {
moveRight(id, speed);
}, 50);
}
moveRight('test', 1);
</script>
A jsfiddle to play with. You can tweak it to your liking.

Categories

Resources