Change image after number of clicks using javascript - javascript

I have a counter set to 100, i want that by clicking on default.jpg image the countdown begin to count the mouse clicks maded.
Now it works only by clicking on the href not over the image.
I also want that when the counter reach 50/25 click the image change with another one.
To understand better i need to make a simple breck the egg "tamago" game, i have no js skills.
Here is what i've done:
<html>
<head>
<script type="text/javascript">
var clicks = 100;
function linkClick(){
document.getElementById('clicked').value = --clicks;
}
document.write('Click Me!');
</script>
<script type ="text/javascript">
function changeimage()
{
if (clicks==100)
{
document.getElementById('myimage').src="defaul.jpg";
}
if (clicks==50)
{
document.getElementById('myimage').src="crack1.jpg";
}
if (clicks==25)
{
document.getElementById('myimage').src="crack2.jpg";
}
</script>
<img src="1.jpg" id="myimage" alt="" onmousedown="changeimage()">
clicks:<input id="clicked" size="3" onfocus="this.blur();" value="10" > times.
</body>
</html>
Thank you

This would be a nice way of doing it. It's easy to read, and hopefully makes sense.
var count = 100;
var image = document.getElementById('myimage');
var images = ['default.jpg', 'crack1.jpg', 'crack2.jpg'];
image.src = images[0];
image.onclick = function(e)
{
if(count > 50)
image.src = images[0];
else if (count > 25)
image.src = images[1];
else if (count > 0)
image.src = images[2];
else
{
//do something here to indicate the end
}
count--;
};

Related

Javascript display dynamic changing image

I want to refresh an image every 1 second. This picture is dynamically generated by my webcam, but this script sometimes display broken images when browser didnt yet load a picture before display. How to detect when picture is loaded and then change the diplay picture?
I have a code like this:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 1000);
</script>
You should wait for the image to be loaded first, before replacing it.
For this, you can use different approaches. What I usually do, is to create another image which is not visible and replace the one visible once the previous image is loaded.
Your code should look like this if you want to follow this approach:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var url = 'webcam.jpg?rand=' + Math.random();
var img = new Image();
img.src = url;
img.addEventListener('load', function() {
var myImageElement = document.getElementById('image');
myImageElement.src = url;
});
}, 1000);
</script>
What you can also do is play with css styles to make the image hidden or visible depending on the state, but that would make your image appear and disappear which is a bit ugly...
I hope it helps :)
I think you can use something like this:
var _img = document.getElementById('pic'),
urlToImage = 'pic.jpg',
modified = false, lastModified = 0;
setInterval(function(){
fetch(urlToImage)
.then(function(resp){
var f = new File([resp],"file");
switch(true) {
case modified === false:
lastModified = f.lastModified;
modified = true; break;
default:
modified = false;
if(lastModified < f.lastModified) {
modified = true;
}
}
return resp.blob();
})
.then(function(blobdata){
switch(true) {
case modified === true:
var obj_url = URL.createObjectURL(blobdata);
_img.src = obj_url;
break;
}
});
},1000);
<img src="" id="pic" alt="LOCAL pic here"/>
I think that looking at lastModified time in File properties is a good way to assume image was finished written on the server.
Hope this helps.
Try using this after loading the document
$( document ).ready(function() {
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 500);
});
Hope this helps

JavaScript while loop error: Unexpected token

So I have made a code for some coursework, the code is suppose to start a function on page load which will then run the function of changing the traffic light image on screen. It is suppose to keep on changing forever however the program crashes or fails to load when I try to run. Before you suggest the problem is that the variable used in the condition isnt changed, I have tried to change it in the following code. when I ran it in the chrome debugger this is the thing that came up; 'Uncaught SyntaxError: Unexpected token <'.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"r.jpg",
"randy.jpg",
"g.jpg",
"y.jpg"
];
var counter = 0;
function start() {
counter = counter + 1;
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=images[counter];
}
var a = 100;
function infinity() {
while (200>a) {
setTimeout(start(), 3000);
}
a = a - 25;
}
</script>
</body>
</html>
Instead of setting while loop and setTimeout, use setInterval. The below code will work I think. It will change the image 100 times
var url="http://www.hdwallpapers.in/thumbs/2017/";
var a=0,Handler;
var images = ["yosemite_national_park_winter_4k-t1.jpg","namib_coastal_desert_4k-t1.jpg","beach_dock-t1.jpg"];
var counter = 0;
function start() {
counter = counter + 1;
a++;
if(a>=100 && Handler)
clearInterval(Handler);
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=url+images[counter];
return;
}
function infinity() {
Handler=setInterval(start, 3000);
}
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="http://www.hdwallpapers.in/thumbs/2017/yosemite_national_park_winter_4k-t1.jpg">
<script>
</script>
</body>
</html>
I know that this question already has an answer, but i just figured that the following code might be a better and a relatively simpler way of doing it.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"red.JPG",
"green.jpg",
"randy.jpg",
"yellow.JPG"
];
function infinity() {
var counter = 0,
image = document.getElementById("trafficlight"),
a = 5,
timeoutInterval = 3000;
setInterval(function() {
counter++;
if(counter == images.length) counter=0;
if (a>=0) {
image.src=images[counter];
a--;
}else{
// this else case is in the event that the timeout
// variable is 1, which is essentially 1ms, which
// is bad as it would make your cpu usage go to a
// 100%
if (timeoutInterval <= Number.MAX_SAFE_INTEGER - 2) {
// the above if condition is to stop timeoutInterval
// from ever reaching 2^53 which would cause an
// overflow
timeoutInterval *= 2;
Math.pow(timeoutInterval, 20);
}
}
}, timeoutInterval);
}
</script>
</body>
</html>
Thanks!
P.S. my laptop is still hot from running your infinite loop code of an example

Manual traffic light conversion into automatic via Javascript

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going? Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>
To make this automatic, you can either put it in a loop, or you can use the setInterval function.
var interval = setInterval(nextLightClick, 1500);
This will loop indefinitely, running the function every 1500 milliseconds (1.5 seconds). If you want to stop it, you can simply say:
clearInterval(interval);
Here's an example -- note that I am changing the innerHTML, rather than the src, and I am using a div instead of image, but the logic will be exactly the same.
var tlight = new Array("1green.jpg","2yellow.jpg","3red.jpg");
var index = 0;
var tlightLen = tlight.length;
var image = document.getElementById('firstlight');
image.innerHTML = tlight[index];
var interval;
function startInterval() {
interval = setInterval(nextLightClick, 1500);
}
function stopInterval() {
clearInterval(interval);
}
function nextLightClick() {
index++;
if (index == tlightLen)
index = 0;
image.innerHTML = tlight[index];
}
<span id="firstlight"></span></br>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>

How to add prev and next button in slide show

I just made this program for slide show it is working well but i want to use previous and next buttons in the slide show and i don't have any idea how to do that so i put this here please help for the same
var image1=new Image()
image1.src="slide/23.jpg"
var image2=new Image()
image2.src="slide/7.jpg"
var image3=new Image()
image3.src="slide/4.jpg"
var image4=new Image()
image4.src="slide/5.jpg"
var image5=new Image()
image5.src="slide/6.jpg"
</script>
<img id="myImg"src="slide/2.jpg" name="img" width="1000" height="250"/>
<script>
var step=1
function slideImages(){
if (!document.images)
return
document.images.img.src=eval("image"+step+".src")
if (step<5)
step++
else
step=1
setTimeout("slideImages()",3000)
}
slideImages()
</script>
You probably want to abstract away some code so it can be easily reused in your functions:
// Dealing with the counter:
var step;
var steps = 5;
function increment() {
s = (s + 1) % steps;
}
function decrement() {
s--;
if (s<0) s = steps-1;
}
// Dealing with the slide show:
function show() {
document.images.img.src=eval("image"+step+".src")
}
function next() {
increment();
show();
}
function prev() {
decrement();
show();
}
// Automatic sliding:
window.setInterval(next, 3000);
Also, i would reconsider your approach to storing images:
function createImgBySource(src){
var img = new Image();
img.src = src;
return img;
}
var images = [
createImgBySource('slide/23.jpg'),
createImgBySource('slide/7.jpg'),
createImgBySource('slide/4.jpg'),
createImgBySource('slide/5.jpg'),
createImgBySource('slide/6.jpg')
];
Now you can change the increment and decrement functions to use images.length instead of steps, so you can add more images without having to alter other variables. Also, your show() function should look like this (getting rid of the nasty eval):
function show() {
document.images.img.src = images[step];
}
Try the below code
var ss = new TINY.fader.init("ss", {
id: "slides", // ID of the slideshow list container
position: 0, // index where the slideshow should start
auto: 0, // automatic advance in seconds, set to 0 to disable auto advance
resume: true, // boolean if the slideshow should resume after interruption
navid: "pagination", // ID of the slide nav list
activeClass: "current", // active class for the nav relating to current slide
pauseHover: true, // boolean if the slideshow should pause on slide hover
navEvent: "click", // click or mouseover nav event toggle
duration: .25 // duration of the JavaScript transition in seconds, else the CSS controls the duration, set to 0 to disable fading
});
got from Here also here is a sample Fiddle
I would consider using something like jCarousel.
I think you are best putting all of your images into an array and then looking over it. I am assuming that the image tag with the ID 'myImg' is the one that you want to update, as such you should use document.getElementByID('myImg') and not document.images.img.src=eval("image"+step+".src") -- eval should also be avoided as the performance is poor and it can be dangerous.
Put this as the end of your page:
<script type="text/javascript">
(function(){
var step = 0;
var images = [image1, image2, image3, image4, image5];
var image = document.getElementByID('myImg');
var slideImages = function() {
image.src = images[step].src;
step++;
if (step == images.length){
step == 0;
}
setTimeout("slideImages()", 3000);
};
slideImages()
})();
</script>

Optimizing performance of a javascript image animation

I've got a question in regards to javascript and dynamically displaying images to
form an animation.
The pictures I have are around 1360x768 in size and quite big despite being .png pics.
I've come up with a code for switching out the pics dynamically, but even run on a local
webserver it is too slow (thus sometimes I see the pic being built).
So my question is: is there a better way to do this than dynamically switching out
the "src" part of the image tag, or is there something else that could be done in combination with that, to make sure that the user doesn't have any strange phenomenons
on the client?
<script>
var title_index = 0;
function display_title()
{
document.getElementById('picture').src=
"pics/title_" + title_index + '.png';
if (title_index < 100) {
title_index = title_index + 5;
setTimeout(display_title,3000);
}
}
</script>
<body onload="setTimeout(display_image,3000)">
<image id="picture" src="pic/title_0.png"/>
</body>
Thanks.
I've had this problem too, even when preloading the images into the cache,
Google's The Hobbit experiment does something interesting. They do low resolution while animating and switch it for a hiresolution if you "pause" (stop scolling in the case of The Hobbit experiment). They also use the HTML5 canvas tag to smooth out the animation.
Here's their blog post about their method:
http://www.html5rocks.com/en/tutorials/casestudies/hobbit-front-end/
Their end product:
http://middle-earth.thehobbit.com
Edit:
Pre loading example:
<!Doctype html>
<head>
<title>test</title>
</head>
<body>
<canvas id="myCanvas" width="1360" height="768"></canvas>
<script type="text/javascript">
var images = {};
var loadedImages = 0;
var numImages = 0;
var context = '';
function loadImages(sources, callback)
{
// get num of sources
for(var src in sources)
{
numImages++;
}
for(var src in sources)
{
images[src] = new Image();
images[src].onload = function()
{
if(++loadedImages >= numImages)
{
callback(images);
}
};
images[src].src = sources[src];
}
}
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
var sources =
{
frame0: 'http://piggyandmoo.com/0001.png',
frame1: 'http://piggyandmoo.com/0002.png',
frame2: 'http://piggyandmoo.com/0003.png',
frame3: 'http://piggyandmoo.com/0004.png',
frame4: 'http://piggyandmoo.com/0005.png',
frame5: 'http://piggyandmoo.com/0006.png',
frame5: 'http://piggyandmoo.com/0007.png',
frame5: 'http://piggyandmoo.com/0008.png',
frame5: 'http://piggyandmoo.com/0009.png'
};
var width = 1360;
var height = 768;
var inter = '';
var i = 0;
function next_frame()
{
if(numImages > i)
{
context.drawImage(images['frame' + (i++)], 0, 0);
}
else
{
clearInterval(inter);
}
}
loadImages(sources, function(images)
{
//animate using set_timeout or some such...
inter = setInterval(function()
{
next_frame();
}, 1000);
});
</script>
</body>
Code modified from: www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/
You could overcome this issue by preloading the images on page load. This means that the images would then be stored in memory and immediately available to you. Take a look at the following:
JavaScript Preloading Images
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Categories

Resources