Getting an error saying too much recursion. The actually has to move the image. Its giving the same error even if I am trying to clear the timeout.
Note: I found out that the_image.style.left is not moving the image whatsoever.
<!DOCTYPE HTML>
<html>
<head>
<style>
.image_style{left:x}
</style>
<script>
var the_timer, x_position = 0, my_image;
function move_image(){
my_image = document.getElementById("imag");
x_position = x_position+1;
my_image.style.left = x_position;
the_timer = setTimeout(move_image(), 200);
}
</script>
</head>
<body onclick="move_image()">
<img src = "desert.jpg" id = "imag"
style="position:obsolute; width:300px; height:400px; left:0">
<script>
my_image = document.getElementById("imag");
alert(my_image.style.left);
</script>
</body>
</html>
You need to call setInterval instead of setTimeOut. Right now you are calling function within function which is a never ending process that's why you are getting error.
Also left property needs value in px while you are assigning only a number which will not move the image.
setInterval(function () { move_image() }, '1000');
function move_image() {
my_image = document.getElementById("imag");
x_position = x_position + 1;
my_image.style.left = x_position + "px";
console.log(x_position);
}
Related
I was looking in other posts for the answer, but the answers never seem to work in my favor. I'm trying to make an image fade when the page finishes loading. I've figured out I can loop until the counter reaches 0 (when image is invisible) and fade the image slowly.
The problem is, the setTimeout() function doesn't seem to be working.
Here's the code:
function timeout() {
setTimeout(function () {
//A comment said something about looping,
//but it was confusing to understand...
}, 50);
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 0 //Start at being visible
for (var i = 10; i > 0; i = i - 0.1) { //For loop
load.style.opacity = i; //Use the index variable and use that to set the opacity
setTimeout(); //Set the timeout, but this function does not pause the program for some reason...
//I need to pause for 0.05 seconds.
}
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
I put the javascript in a seperate file, I just can't access it from Stack Overflow...
Can someone help? And also, sometimes the image can be finicky at times as well, like sometimes it won't hide like it's supposed to do. Thanks!
You declared a setTimeout without arguments, hence the error:
'Window': 1 argument required, but only 0 present."
Give it the appropriate amount of arguments:
for (var i = 10; i > 0; i = i - 0.1) { //For the loop
load.style.opacity = i;
setTimeout(functionName, milliseconds);
}
If you intended to use your timeout() function instead, call it. You're just instantiating a new setTimeout from the one you already created in the timeout() function.
You can use a recursive function instead of a loop
var load = document.getElementById('img');
function setup() {
load.style.opacity = "1"; //Start at being visible
timeout(1);
}
function timeout(i) {
setTimeout(function() {
i -= 0.1;
if(i<=0)
return;
load.style.opacity = i.toString();
timeout(i);
}, 200);
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div>
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150" id="img">
</div>
</body>
</html>
Basically you want to countdown the opacity with a recursive call. Here we are going from 1 down to 0 in 0.01 increments. The setTimeout will trigger the next recursive call after pausing for 50 msecs. These values, can of course, be adjusted as needed but the opacity needs to be a number from 1 (visible) to 0 (invisible).
function setOpacity(el, lvl) {
el.style.opacity = lvl;
}
function countDown(el, lvl) {
function action(el, lvl) {
return function () {
countDown(el, lvl);
}
}
setOpacity(el, lvl);
if (lvl > 0) {
lvl -= 0.01
setTimeout(action(el, lvl), 50);
}
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 1; //Start at being visible
countDown(load, 1);
}
window.addEventListener('load', setup, true);
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
function setup() {
var load = document.getElementById('img');
(function(){
var i = 1;
setTimeout(function () {
i -= 0.1;
load.style.opacity = i;
if (i > 0) {
setTimeout(arguments.callee, 100);
}
}, 100);
})();
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
I'm very new to javascript and EaseLJS but I don't understand how this doesnt work.
I have a html file:
<!DOCTYPE html>
<html>
<head>
<script src="easeljs-0.7.1.min.js" type="text/javascript"></script>
<script src="game.s.js" type="text/javascript"></script>
<script>
function init() {
renderLevel();
}
</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="500" height="300">
alternate content
</canvas>
</body>
</html>
The game.s.js file looks like:
function renderLevel()
{
var stage = new createjs.Stage("canvas");
var bitmap = new createjs.Bitmap("brick.png");
stage.addChild(bitmap);
bitmap.x = 32;
bitmap.y = 32;
stage.update();
alert(stage.canvas);
alert(bitmap.name);
}
The alert I just put there to check the values. stage.canvas rightly points to the HTML5Canvas element but the image won't show!
What am I missing here? :)
Thank you
The problem is that you are adding the image to stage before it loads, then there's no image yet. You need to wait for the image to load before adding it to the stage.
You can do this by using a preload(); function to load all the images before calling init(); or renderLevel();. Here's what this function should look like:
function preload(images, callback) {
var count = images.length;
if (count === 0) {
callback();
}
var loaded = 0;
$(images).each(function () {
$('<img>').attr('src', this).load(function () {
loaded++;
if (loaded === count) {
callback();
}
});
});
}
...and then you can use it like so:
preload(["image1.png", "image2.png"], init());
I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}
I am having some major problems with a javascript app I'm working on. I want my window to open to a closed envelope and then after five seconds to change to an open envelope with a little 1 counter in the corner of it. I want the counter to continue to move up every five seconds unless the envelope is clicked. If clicked I want the count to start over. So far I have only gotten my closed envelope showing up. I'm new and have no idea what I am doing wrong so any help would be awesome!
My html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"closed" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
And my JavaScript:
window.onload = function(){
var counter = 0;
var timer = setInterval(
function(){
counter++;
document.getElementById("demo").firstChild.nodeValue = counter;
},
5000
);
function openEnvelope(){
var img = document.getElementById("picture");
if (counter > 1){
img.src = "open.png"
}
}
open = setTimeout("open()", 1000);
function resetTimer(){
clearInterval(timer);
}
}
You need to increment your counter and set the counter span to have that value :
var counter = 0;
//Create your timer (setTimeout will only run once, setInterval will start again once run.
//1000 = 1 second
var timer = setInterval(openEnvelope, 1000);
function openEnvelope() {
var img = document.getElementById("picture");
var counterSpan = document.getElementById("counter");
if (counter > 1) {
img.src = "open.png"
counterSpan.innerHTML = counter;
}
//Add 1 to Counter
counter++;
}
function resetTimer() {
clearInterval(timer);
counter = 0;
}
This will run your openEnvelope function every second, and if the counter value is more than 1 it will set the Img Source to be open.png and the counter span to have the counters value. On the click of the Envelope it will clear the timer and reset the counter.
And your HTML will become :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"picture" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
Here is a working JSFiddle for your problem, try creating a blank page and copying the HTML straight into the <body> tag and the Javascript into <script></script> tags in the <head> of your page.
I am using javascript to periodically replace a .png picture, which ist viewed fullscreen as the only content of a site. No matter how I try, in Firefox, after being loaded (as seen via firebug), the new image is always drawn from top to bottom. This takes some seconds. Is there any way to prevent this and show the picture all at once?
This is my current javascript code:
function preloadScreenshotPeriodically(){
var new_screenshot = new Image();
new_screenshot.src = "screenshot.png?defeat_firefox_caching=" + counter;
new_screenshot.id = "screenshot";
counter = counter + 1;
new_screenshot.onload = function(){
loadScreenshot(new_screenshot);
setTimeout("preloadScreenshotPeriodically();", 5000);
};
}
function loadScreenshot(new_screenshot){
document.getElementById("screenshot").parentNode.replaceChild(new_screenshot, document.screenshot);
}
I also tried to use two images, one of them hidden. Then loading the picture in the hidden one and swapping them. Same results :/
In an other version, I fetched the image with Ajax and after loading is complete, changed the url of the img-tag. My hope was, that the browser would recognize the picture had already been loaded and fetch it from the browsercache rather than loading it. But this didn't happen and I ended up with two requests to the server for one picture and the same slow drawing of it as in my other trys.
edit:
Now I tried it like suggested in answer 1. While it works just fine if I switch the picture when I load the next one (I don't want this), trying to switch it as soon as it is loaded (what I want) results in a blank window (very short) and visible loading of the picture as described above.
this works:
<body>
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showFirstImage() {
loadNextImage();
}
function showNewImage() {
loadNextImage();
}
function nextImageLoaded() {
// swapImage();
}
function loadNextImage() {
swapImage();
screenshotCount = screenshotCount +1;
var nextImage = "<img id='loaderWinImg' src='screenshot.png?x="+screenshotCount+"' onload='nextImageLoaded()' />";
document.getElementById('loaderWin').innerHTML = nextImage;
}
function swapImage() {
document.getElementById("loaderWinImg").onload = '';
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
}
var showImages = setInterval("showNewImage()",15000);
showFirstImage();
</script>
</div>
</body>
</html>
this doesn't work:
<body>
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showFirstImage() {
loadNextImage();
}
function showNewImage() {
loadNextImage();
}
function nextImageLoaded() {
swapImage();
}
function loadNextImage() {
screenshotCount = screenshotCount +1;
var nextImage = "<img id='loaderWinImg' src='screenshot.png?x="+screenshotCount+"' onload='nextImageLoaded()' />";
document.getElementById('loaderWin').innerHTML = nextImage;
}
function swapImage() {
// loadNextImage();
document.getElementById("loaderWinImg").onload = '';
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
}
var showImages = setInterval("showNewImage()",15000);
showFirstImage();
</script>
</div>
</body>
</html>
The problem can be seen here (in firefox problem like described above, in chrome there are no pauses between pictureloads and there is a blank window in between picture changes): http://sabine-schneider.silbe.org:1666/test.html
And here, what Rob suggested in answer 1 without any changes (displays the picture fine in firefox, but not in chrome - there I get a blank window in between picture changes): http://sabine-schneider.silbe.org:1666/test0.html
sounds like the image is "progressive" ( interlaced) and the preload needs more time for it to complete download.
You can set a width and height to the image also for a more stable presentation
( poss )
using
?defeat_firefox_caching=" + counter;
means you never cache the image ( which has confused me about your question ) - remove that line( unless you need it for something you haven't mentioned)
update: Can you try ...
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showNewImage() {
screenshotCount = screenshotCount +1;
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
var nextImage = "<img src='screenshot.png?defeat_firefox_caching="+screenshotCoun+"'/>";
document.getElementById('loaderWin').innerHTML = nextImage;
}
var showImages = setInterval("showNewImage()",5000);
</script>