displaying one image, then another using HTML - javascript

I asked a similar question elsewhere, but I am trying to switch from one image to the next after 500 ms. Somebody provided this answer, but the code only works when I preview it in the HTML and Javascript boxes of the site i'm using (then displays nothing when I launch it):
<html>
<head>
<title>switch</title>
<script type = "text/javascript">
var images = [];
var x = 0;
var $img = document.getElementById("img");
images[0] = "image1.jpg";
images[1] = "image2.jpg";
function displayNextImage() {
if (++x < images.length) {
$img.src = images[x];
setInterval(displayNextImage, 500);
}
else {
$img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>
Is there a way to get this to work in HTML only? I tried doing this, but it only stays on the first image:
<html>
<head>
<title>switch</title>
</head>
<body>
<img id="img" src="http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg"
alt="" />
<script>
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
function startTimer() {
setInterval(displayNextImage, 500);
}
</script>
</body>
</html>
Also, jQuery doesn't work on the site i'm using.

You never actually call the startTimer function.
Try adding startTimer(); before the script tag is closed.
Your first code had an onload event on the body, which would execute your function.
UPDATE (you're also missing a curly bracket on your if statement in displayNextImage())
<script type="text/javascript">
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
} else {
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
</script>

You just need to invoke the startTimer() function.
Read about JavaScript Function Invocation.
Also note that you missed closing the displayNextImage() function.
Replace your <script> code block with this one:
<script>
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
</script>
Here is the working code snippet:
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
<img id="img" src="http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg"
alt="" />

Related

Weird action by javascript for onclick event

Hi! I'm trying to create a carousel/image slider which is automatic and reactable to onclick event but for somereason the onclick event messesup the automatic flow of the slider even though the code makes perfect sens!
Could someone tell me whats wrong in this code and a solution to fix it please! thank you!
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
prevbutton.addEventListener("click",leftbuttonclick);
function rightbuttonclick(){
i++;
changeImg();
}
function leftbuttonclick(){
i--;
changeImg();
}
function changeImg(){
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
function changenext(){
i++;
changeImg();
}
// Run function when page loads
window.onload=changeImg;
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200"/>
<button id="rightbutton">right</button>
here is a code that can help you,
var prevbutton=document.querySelector("#leftbutton");
//nextbutton.addEventListener("click",leftbuttonclick);
prevbutton.addEventListener("click",leftbuttonclick);
Keep a variable eg: setTime that decides whether to call setTimeout again or not.
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload = changeImg();
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
Or you can use setInterval instead of setTimeout as shown below:
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
}
window.onload = changeImg();
setInterval(function() {
changeImg()
}, time);
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
add a clearTimeout function to chageImg() and it will work,
as to why it was behaving strangely is because setTimeout was been called multiple times. you should always be careful when using setInverval or setTimeout. here is a code snippet
function changeImg(){
clearTimeout(interval);
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
interval = setTimeout("changeImg()", time);
}

How do i make html code go into colour?

If you put this into sublime it doesnt work. can anyone help me? its meant to be traffic lights that stay stationary. please can someone help? im not allowed to use adbanner but dont know how to make it work
<!DOCTYPE html>
<html>
<body>
function changeImage()
{
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length){
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade){
if(fade === true){
val--;
}else{
val ++;
}
if(val > 0 && val < 100){
el.style.opacity = val / 100;
setTimeout(function(){fadeImg(el, val, fade);}, 10);
}
}
var images = [],
x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
<img id="img" src="startpicture.jpg">
You can do below changes to your script for successful execution of the script:
// below script will be in script tag
var images = [],
x = 0;
$(document).ready(function() { // put below script in document.ready()
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
});
function changeImage()
{
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length){
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 500);
}
function fadeImg(el, val, fade){
if(fade === true){
val--;
}else{
val ++;
}
if(val > 0 && val < 100){
el.style.opacity = val / 100;
setTimeout(function(){fadeImg(el, val, fade);}, 10);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<img id="img" src="startpicture.jpg">

Make JavaScript change background image every 5 seconds

I am trying to change my background image every 5 seconds. How should I go about this?
window.onload = function () {
function Timer() {
window.setInterval("changeImage()", 5000);
}
function changeImage() {
var BackgroundImg["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"];
var i = Math.floor((Math.random() * 3));
var bgImg = document.body.style.backgroundImage();
bgImg.url = BackgroundImg[i];
}
}
You can make few changes
1.Not sure from where you are calling Timer function (better if
have camelCase)
function Timer() {
window.setInterval("changeImage()", 5000);
}
Instead you can directly use
setInterval(changeImage, 5000);
changeImage is a callback
2.Could not make out what is this line mean
var bgImg = document.body.style.backgroundImage();
Unsure if can attach a function to style property.
Anyway this below snippet can be useful
window.onload = function () {
// Array of Images
var backgroundImg=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g",
"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.body.style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
DEMO
you are accessing style incorrectly
window.onload = function () {
function changeImage() {
var BackgroundImg=["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"
];
var i = Math.floor((Math.random() * 4));
document.body.style.backgroundImage = 'url("' + BackgroundImg[i] + '")';
}
window.setInterval(changeImage, 5000);
}
Also, if possible (usually is) don't pass a string to window.setInterval - use as above
Here's a solution to your question. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function changeImage() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg";
images[1] = "http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg";
images[2] = "http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg";
</script>
</head>
<body onload = "changeImage()">
<img id="img" src="http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg"/>
</body>
</html>

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

Javascript changing an image within a div after a certain amount of time

I am currently making a web page with an image inside of a div tag. I wrote a script to change the image after a certain amount of time, and it works fine when I test the script alone, however; when I attempt to place the script within my web page, it does not change the image.
Here is the code for my script:
<!DOCTYPE html>
<html>
<body>
<script>
images = new Array;
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
setInterval( function() {
changeImage()
}, 5000);
x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if ( x < 8 ) {
x += 1;
} else if ( x = 9 ) {
x = 0;
}
}
</script>
<img id='ad' src="img.gif">
</body>
</html>
I have tested this script with the image inside of a div tag and it still works fine. When I put the same code into my web page, it does not work. Also note, the image file names are just examples. The images I am using are from photobucket, so I have very little control over what they are called. Any help I could get on this would be greatly appreciated.
You need to put your code inside window.onload = function() {}
var images = new Array();
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
function changeImage() {
document.getElementById('ad').src = images[x];
if (x<8) {
x+=1;
}
else if (x===9) {
x=0;
}
}
window.onload = function() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
Edit
This code has been tested on my local machine and works.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var images = new Array();
for (var i = 2; i < 11; i++) {
images.push("img" + i + ".gif");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
document.getElementById('imgsrc').innerHTML = "<h1>" + images[x] + "</h1>";
if (x < 8) {
x += 1;
} else {
x = 0;
}
}
window.onload = function() {
setInterval(function () {
changeImage();
}, 1000);
}
</script>
</head>
<body>
<img id="ad" src="img.gif" />
<div id="imgsrc"><h1>img.gif</h1></div>
</body>
</html>
Here is a fiddle of the final code working. JSFiddle doesn't like window.onload for some reason, so I had to exclude it. This doesn't really demonstrate my point, but I thought I'd just include it anyway.
Your code works to change the image src in this fiddle: http://jsfiddle.net/snB2a/1/
Try to rename your variables images and x to longer names. What can happen is, if some other code in your page, or worse, some code in one of the script file you page references, use variable "x" without declare it locally, then it would actually modify your "x" variable.
Here is an example to demonstrate the problem:
function something()
{
for (x = 0; i < 10; x++)
dosomethingelse();
}
If the above function is called in your page, then it will overwrite your "x" variable. The following code is safe:
function something()
{
var x;
for (x = 0; i < 10; x++)
dosomethingelse();
}

Categories

Resources