Why does the slide of my javascript carousel not reset? - javascript

I have a carousel that goes through the slides every 4 seconds if the user doesn't click on anything. However, the problem I am getting is that if, for example, the user clicks on a slide after 1 second, and then the next one after 2 seconds, the following slides don't appear 4 seconds later. The js code is below:
var arr = [];
arr[0]= new Image();
arr[0].src = "1.jpg";
arr[1]= new Image();
arr[1].src = "2.jpg";
arr[2]= new Image();
arr[2].src = "3.jpg";
titleArray = new Array();
titleArray[0] = "first";
titleArray[1] = "second";
titleArray[2] = "third";
var i=0;
function slide(){
document.getElementById("img1").src= arr[i].src;
document.getElementById("title").innerHTML = titleArray[i];
i++;
if(i==arr.length){
i=0;
}
setTimeout(function(){ slide(); },4000);
}
The html is:
<!doctype html>
<html lang="en">
<head>
<title>Carousel</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body onLoad="slide();">
<div class="image">
<img src="1.jpg" width="510" height="390" id="img1">
<a href="JavaScript:slide(this)">
<img src="carousel-label-box.png" id="img2" width="310" height="190">
</a>
<h1 id="title">first</h1>
</div>
<script src="script.js"></script>
</body>
</html>

You mean when the user clicks on the images the slide will change before the intended 4 seconds?
From what I see you should call clearTimeout() to interrupt it and then set it again when the user clicks on the images instead of simply calling slide.
EDIT: Forgot to mention you should still call slide() function when the user clicks it.

Related

How do you make a sound play when a hyperlinked image/text is clicked (still taking you to the hyperlinked webpage)

I'm doing an SDD assessment and I'm making a website kind of game. It will be a choose your own adventure game and I'm trying to incorporate JavaScript. I have 3 buttons that will take the user to different pages and I would like each of the buttons to make a sound when they're clicked. The buttons are text with a sword image above them, so I'd like a sword sound to play. However, I'm not experienced with JavaScript. I found some code for it at https://www.daniweb.com/programming/web-development/threads/286059/play-sound-when-a-link-is-clicked
but it means nothing to me cause I don't know how to use it. Would someone be able to explain to me what it means and how to adapt it to my HTML and CSS?
Here's my HTML code
<html>
<head>
<meta charset="UTF-8">
<title>SDD Minor Project Code</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/js" href="script.js">
</head>
<body>
<div class="home_sword">
<a href="https://trinket.io/html/c11627b947?outputOnly=true&runMode=autorun">
<img id="home_button_img" src="button_underline_sword_left.png">
<h2><i>Home</i></h2>
</a>
</a>
</div>
<div>
<img class="left_shield" src="shield_title_bookend.png">
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png">
</div>
<img class="scroll" src="story_scroll.png">
<div class="narrative">
<p>Hello, World!</p>
</div>
</body>
</html>
Here's an exemple of what i made on one of my projects when i was learning JavaScript
<script>
function soundAlarm() {
let amount = 3; // count of sound you want here is set on 3 but you can change it as much you want
let audio = new Audio("Timer_Sound_Effect.mp3"); //here variable for the src of the sound
function playSound() { // function that plays the sound
audio.pause();
audio.currentTime = 0;
audio.play();
}
for (let i = 0; i < amount; i++) { // loop to play as many times you asked in "let amount "
setTimeout(playSound, 1200 * i); // 1200 = 1200 mseconds between each times the sound plays.
}
}
</script>
In html just put as attribute to play it:
<html>
<head>
</head>
<body>
<div>
<img class="left_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
</div>
</body>
</html>
Here's your code with the modifications :) :
<html>
<head>
<meta charset="UTF-8">
<title>SDD Minor Project Code</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/js" href="script.js">
</head>
<body>
<div class="home_sword">
<a href="https://trinket.io/html/c11627b947?outputOnly=true&runMode=autorun">
<img id="home_button_img" src="button_underline_sword_left.png">
<h2><i>Home</i></h2>
</a>
</a>
</div>
</a>
</a>
</div>
<div>
<img class="left_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
</div>
<img class="scroll" src="story_scroll.png">
<div class="narrative">
<p>Hello, World!</p>
</div>
</body>
<script>
function soundAlarm() {
let amount = 3; // count of sound you want here is set on 3 but you can change it as much you want
let audio = new Audio("Timer_Sound_Effect.mp3"); //here variable for the src of the sound, change it by the path of your file, or directly by your file name if in same folder.
function playSound() { // function that plays the sound
audio.pause();
audio.currentTime = 0;
audio.play();
}
for (let i = 0; i < amount; i++) { // loop to play as many times you asked in "let amount "
setTimeout(playSound, 1200 * i); // 1200 = 1200 mseconds between each times the sound plays.
}
}
</script>
</html>

How would I add a download link into the second image of this script

This is the script I am working with (below)
As the images are built into the script I am unsure on how to add a download link/link to website. to the second image
The script changes from image 1 to image 2 after 10 seconds and then I want then to be able to CLICK image 2 (like a button)
Here is the script I am working with if you could maybe help me with adding it in or tell me what I need to add in and where that would be much appreciated
<!DOCTYPE html>
<head>
<title>Demo</title>
</head>
<body>
<img id="img1" src="https://i.makeagif.com/media/1-28-2016/N_tuzx.gif" />
<script>
setTimeout(function(){
document.getElementById("img1").src = "https://2.bp.blogspot.com/-fgPjlOk4PWc/WzQrQ_NBxRI/AAAAAAAAAWw/bvINTos17nssgQXqhevQq97dvUfzINdhgCPcBGAYYCw/s320/download-2062197_960_720.png";
}, 10000);
</script>
</body>
</html>
Thank you for your time
After you've changed src of the image, just add a "click" event listener to it
setTimeout(function(){
document.getElementById("img1").src = "link";
document.getElementById("img1").addEventListener("click", function (event) {
// when someone clicks
});
}, 10000);
Use below code and replace Download_Link with desired link
<!DOCTYPE html>
<head>
<title>Demo</title>
</head>
<body>
<div id="wrapper">
<img id="img1" src="https://i.makeagif.com/media/1-28-2016/N_tuzx.gif" />
</div>
<script>
setTimeout(function(){
var mydiv = document.getElementById("img1");
var aTag = document.createElement('a');
aTag.setAttribute('href',"Download_Link");
aTag.setAttribute('download', true);
aTag.appendChild(mydiv);
document.getElementById("wrapper").appendChild(aTag);
document.getElementById("img1").src = "https://2.bp.blogspot.com/-fgPjlOk4PWc/WzQrQ_NBxRI/AAAAAAAAAWw/bvINTos17nssgQXqhevQq97dvUfzINdhgCPcBGAYYCw/s320/download-2062197_960_720.png";
}, 10000);
</script>
</body>
</html>

assigning <img> element as a value for a javascriptvariable

I am creating a to do list app with Javascript and I want to use a .png image to show a delete and complete icon. I created two variables for the images and used <img src="images/complete.png" height="30"> as the value of the variables. However when I load on the browser the images do not show.
Snapshot of app
var image1 = '<img src="images/deleteicon.png" height="30" >';
var image2 = '<img src="images/complete.png" height="30" >';
document.getElementById('add').addEventListener('click', function(){
var value = document.getElementById('item').value;
if(value){
addItemToDo(value);
}
})
function addItemToDo(text){
var list = document.getElementById('todo');
var item = document.createElement("li");
item.innerText = text;
var buttons = document.createElement("div");
buttons.classList.add("buttons");
var remove = document.createElement("button");
remove.classList.add("remove");
remove.innerHtml = image1;
var complete = document.createElement("button");
complete.classList.add("complete");
complete.innerHtml = image2;
buttons.appendChild(remove);
buttons.appendChild(complete);
item.appendChild(buttons);
list.insertBefore(item, list.childNodes[0]);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To Do List</title>
<link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">
<link type="text/css" href="Css/style.css" rel="stylesheet">
</head>
<body>
<header>
<input placeholder="Enter a task" id="item">
<button type="button" ><img src="images/add.png" alt="Add" height="30" id="add"></button>
</header>
<div class="container">
<ul class="todo" id="todo">
<li>
This is an Item
<div class="buttons">
<button class="remove" ><img src="images/deleteicon.png" alt="Add" height="30" id=""></button>
<button class="complete"><img src="images/complete.png" alt="Add" height="30" id=""></button>
</div>
</li>
</ul>
</div>
<script type="text/javascript" src="Js/main.js">
</script>
</body>
</html>
However when I load on the browser the images do not show.
It is because you are trying to do it the wrong way. The idea here is to create html element and then assign src attribute to it as #Lucky Soni has shown. However, I would like to improve his solution. Notice, that the image can be huge or some network issues may occur. It might significantly delay image loading and if you don't handle this situation properly, your users are likely to see the browsers' default broken image icon or the image itself slowly loading into the page. To handle this situation you can use onload event for <img> like this:
function loadImage(elem, imgPath, callback) {
var newImg = new Image();
newImg.onload = function() {
// insert it into the page. this is equal to newImg - our image element
elem.appendChild(this);
// you can do something else passing down image or element to a callback function
callback(this);
}
newImg.src = imgPath;
newImg.classList.add("img");
}
var elem = document.getElementById('test');
var imgPath = 'http://rcysl.com/wp-content/uploads/2017/02/Pics-Of-Nature-HD-.jpg';
loadImage(elem, imgPath, otherfunction);
function otherfunction(param) {
console.log('Some action with ' + param);
}
.img {
width: 50%;
border: 1px solid orange;
display: block;
}
<div id="test">My image:</div>
The above is very simple example based on callbacks. You might want to use Jquery's Deferred object or native JS Promise object to load images asynchronously and then doing some things when the images are done.
Update:
Preload image on page load
function preloadImage(url) {
(new Image()).src = url;
}
var image1Url = 'http://via.placeholder.com/50?text=Done',
image2Url = 'http://via.placeholder.com/50?text=Remove';
function createImageElement(url){
var image1 = document.createElement('img');
image1.src = url;
return image1;
}
// preload the images
preloadImage(image1Url);
preloadImage(image2Url);
document.getElementById('add').addEventListener('click', function(){
var value = document.getElementById('item').value;
if(value){
addItemToDo(value);
}
})
function addItemToDo(text){
var list = document.getElementById('todo');
var item = document.createElement("li");
item.innerText = text;
var buttons = document.createElement("div");
buttons.classList.add("buttons");
var remove = document.createElement("button");
remove.classList.add("remove");
remove.appendChild(createImageElement(image1Url));
var complete = document.createElement("button");
complete.classList.add("complete");
complete.appendChild(createImageElement(image2Url));
buttons.appendChild(remove);
buttons.appendChild(complete);
item.appendChild(buttons);
list.insertBefore(item, list.childNodes[0]);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To Do List</title>
<link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">
<link type="text/css" href="Css/style.css" rel="stylesheet">
</head>
<body>
<header>
<input placeholder="Enter a task" id="item">
<button type="button" ><img src="images/add.png" alt="Add" height="30" id="add"></button>
</header>
<div class="container">
<ul class="todo" id="todo">
<li>
This is an Item
<div class="buttons">
<button class="remove" ><img src="images/deleteicon.png" alt="Add" height="30" id=""></button>
<button class="complete"><img src="images/complete.png" alt="Add" height="30" id=""></button>
</div>
</li>
</ul>
</div>
<script type="text/javascript" src="Js/main.js">
</script>
</body>
</html>

simple advert changer - each() loop won't delay()

I am trying to create advertisement box which simply changes picture after given time. I used each() loop to hide and display images one after another but all i get is same time effect on all pictures. Any clue how to fix that ?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="advert.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
.advert{
position: relative;
}
.advert img{
position: absolute;
/*visibility: hidden;*/
}
</style>
</head>
<body>
<div class="advert">
<img src="img/img1.jpg" alt="Smiley face" height="" width="">
<img src="img/img2.jpg" alt="Smiley face" height="" width="">
<img src="img/img3.jpg" alt="Smiley face" height="" width="">
</div>
</body>
<script>
$(function(){
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
images.each(function(){
$( this ).fadeToggle(5000).fadeToggle(5000).delay(10000);
console.log($( this ));
});
}
simpleAdvert();
});
</script>
</html>
.each(function) calls the function for each item in the array immediately, which is why the time effect is applied to all items rather than doing what you expect. To get the pictures to show/hide in a loop you need something like a setInterval which calls a function repeatedly. This should work:
$(function(){
var timeToShow = 750;
var timeToFade = 250;
var timeTotal = timeToShow + timeToFade;
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
var index = 0;
images.hide();
$(images[0]).show();
setInterval(function() {
var next = (index + 1) % images.length;
$(images[index]).fadeToggle(timeToFade);
$(images[next]).fadeToggle(timeToFade);
index = next;
}, timeTotal);
}
simpleAdvert();
});
Essentially this hides all images except the first, then fades out the shown picture and fades in the next picture on an interval.
You should call the delay before the fadeToggle method and if you want to show the images one by one you can use the index of the element in the set:
// using fadeIn() method
images.each(function(index) {
// since the indices are zero-based
// the first element is shown without delay
// you can add 1 to the index: 10000 * ++index
$(this).hide().delay(10000 * index).fadeIn(5000);
A suggestion:
function simpleAdvert() {
var section = $('.advert');
var images = section.find('img').hide();
images.each(function(index) {
$(this).delay(10000 * index).fadeIn(5000);
});
}
It's a small extension to working script by concrete_d (Accepted answer).
+ custom time delay with no animation
+ and random slide on the script start
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="advert.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
.advert{
position: relative;
}
.advert img{
position: absolute;
}
</style>
</head>
<body>
<div class="advert">
<img src="img/img1.jpg" alt="Smiley face" height="" width="">
<img src="img/img2.jpg" alt="Smiley face" height="" width="">
<img src="img/img3.jpg" alt="Smiley face" height="" width="">
</div>
</body>
<script>
$(function(){
var timeToShow = 500;
var timeDelay = 5000;
var timeToFade = 500;
var timeTotal = timeToShow + timeToFade + timeDelay;
var minimum = 0;
var maximum = $('.advert').find('img').length - 1;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
console.log(randomnumber);
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
var index = randomnumber;
images.hide();
$(images[randomnumber]).show().delay(timeDelay);
setInterval(function() {
var next = (index + 1) % images.length;
$(images[index]).fadeToggle(timeToFade);
$(images[next]).fadeToggle(timeToFade);
index = next;
}, timeTotal);
}
simpleAdvert();
});
</script>
</html>

JavaScript Slideshow Not Working

I am programming a very simple JavaScript slideshow and it isn't working. I do not want jQuery. This code displays the first image after 5 seconds, however does not cycle through the rest of the images. The full code is as follows, I just can't figure out what I am doing wrong:
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>JavaScript Slideshow</title>
<style>
#slider > img { display: none }
</style>
</head>
<body>
<div id="slider">
<img src="img1.png">
<img src="img2.png">
<img src="img3.png">
<img src="img4.png">
<img src="img5.png">
</div>
<script>
var s = document.getElementById("slider").getElementsByTagName("img");
var c = s.length;
setInterval(function() {
s[(s.length++) % c].style.display="block";
}, 5000);
</script>
</body>
</html>
Your code has several errors in it.
You're trying to increment the array length, and modulo it by the counter. I bet you wanted to do that the other way around:
s[c % (s.length)].style.display="";
You're not hiding the images already cycled through, so your cycle will only display once.
var s = document.getElementById("slider").getElementsByTagName("img");
var c = s.length;
setInterval(function() {
s[c % s.length].style.display="";
s[(++c) % s.length].style.display="block";
}, 5000);

Categories