How to implement image slide show using javascript - javascript

I tried implementing it.But..the image changes from the first to the secnd and then stops.
for your reference,please find the code i tried to implemented.
<div id="images"> <img name="slide" src="img/banner1.png"/>
<script type="text/javascript" >
var slideShow=document.getElementById("images");
var allImages= new Array();
allImages=["img/banner3.png","img/banner2.png","img/banner4.png","img/banner5.png"];
var imageIndex=0;
function changeImage()
{
document.images.slide.src=allImages[imageIndex];
//slideShow.setAtrribute("src",allImages[imageIndex]);
console.log("executing 1");
imageIndex++;
if(imageIndex >= allImages.length)
{
console.log("executing 2");
imageIndex=0;
}
}console.log("executing 3");
setTimeout("changeImage()",1000);
console.log("executing 4");
</script>
</div>
Can Someone,help me in fixing this issue..Please!

This is the similar script you are searching for...
Java Script
slide=new Array("images/2.jpg","images/3.jpg","images/4.jpg","images/5.jpg","images/6.jpg","images/8.jpg")
pic=0;
function start()
{
setInterval("fun()",3000);
}
function fun()
{
document.show.src=slide[pic];
pic++;
if(pic==6)
pic=0;
}
HTML
<body onLoad="start();>
-------
-------
</body>

If you want to make the infinite slide show use setInterval instead of setTimeout.
setInterval('changeImage()',1000);
Your code works as fine after changing it. Enjoy.

Related

How to call a function in external script file from HTML

I'm trying to call a javascript function in my HTML index file and I can't get it to work.
This is my html file that I'm trying to call a function from.
<div class="main">
<h1 class="header-main" onload="HeaderTyper('Welcome', this)">
<noscript>no javascript</noscript>
</h1>
</div>
<script type="text/javascript" src="script.js"></script>
And this is the script.
function HeaderTyper(message, element){
var i = 0;
var speed = 50;
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
I'm trying to get a typewriter effect style header. I'm planning to add some keystroke sounds, but first I need to figure out how to actually type it out in the header tag. The code won't type out the message I'm passing in argument. What did I do wrong ? Thank you for any help.
After the HTML page ends (As #johannchopin explained), import the file and then add an event listener (as #aaronburrows explained).
<body>
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
</body>
</html>
<script type="text/javascript" src="script.js"></script>
<script>
let h1 = document.querySelector('.header-main');
h1.addEventListener('load', HeaderTyper("Welcome", h1, false));
</script>
Also, I fixed the function, it was missing the parameters.
function HeaderTyper(message, element, i) {
var speed = 50;
if (i < message.length) {
console.log(message.charAt(i))
element.innerHTML += message.charAt(i);
//play keystroke sound
setTimeout(function(){ HeaderTyper(message,element,++i)}, speed);
}
}
You're attempting to bind a function call before it is loaded into the browser. Remove the onload from the HTML and add an event listener to the script.
According to this solution, The onload event can only be used on the document(body) itself. Best way to achieve this is to call the function in a <script> tag just before the </body> closing tag:
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
<script>
function HeaderTyper(message) {
var i = 0;
var speed = 50;
var element = document.querySelector('.header-main');
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper('Welcome');
</script>
Ok, hi there.
function HeaderTyper(message, element){
alert('script loaded') //<---
var i = 0;
I put this line at the beginning of the script to make sure it works. And it's not.
Why?
Because you just made your function but doesn't call it.
First way to solve this - put ur function in the "script" of HTML doc. And call it after, like
<script>
function HeaderTyper(message) {
let i = 0
let speed = 50
let element = document.querySelector('.header-main')
if (i < message.length) {
element.innerHTML += message.charAt(i)
i += 1
setTimeout(HeaderTyper, speed)
}
}
HeaderTyper('Welcome') //<---
</script>
Second way - put HeaderTyper() at the end of script.js file, so the function start, but you need to make a link for "message" and "element".
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper(someMessage, someElement) //<---

How do you integrate an incrementing variable into a paragraph

I am trying to make an idle game rather like candy box. I will have a number at the side of the page which rises by one every second. However, the code shown below does not seem to be working. Could anyone tell me why it is not working; how to fix it and where they got their info from. Thank you in advance.
<script type="text/javascript">
var i = 0;
function increment(){
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment(), 1000);
</script>
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
</body>
</html>
You have two issues:
You are calling your script before the DOM is rendered, so at the point the script runs, there is no element with ID of money.
In your setInterval call, you only need the function name (increment) without the parentheses. Including the parentheses (as increment()) only calls the function at that specific moment, rather than referencing it to be called at each interval. (See the Microsoft page on setInterval for more detailed information.)
See this code:
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
<script type="text/javascript">
var i = 0;
function increment() {
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
</script>
change setInterval(increment(), 1000); to setInterval(increment, 1000);
Its not working because as per document https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
it takes a function reference to be executed.. but calling the function increment() like this will only execute once and the return of that function will be used which will be null and not intended hope this clears it
var i = 0;
function increment(){
//console.log(i);
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>

Javascript if statements in displaying images

Hey i am currently trying to get a program running in javascript i want the program to display the 4 images one after each other with the single press of a button and then after the 4 images have cycled through i want them to stop cycling and i cant seem to do it this is my code i currently have:
<html>
<head>
<script>
var images = ["image1.png","image2.png","image3.png","image4.png"];
var imagenum = 0;
var timer;
function imageCycle()
{
if(++imagenum == 4)
imagenum = 0;
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
</script>
</head>
<body>
<img src="image1.png" name="image" width=800 height=600>
<form>
<input type="button" value="images" name="cycle images" onclick="imageCycle()">
</form>
</body>
</html>
any help is appreciated many thanks!
In your code you continue to schedule the function, that's why the images continue to rotate.
If you want to stop at the forth image displayed, you have to put the setTimeout line in an else statement.
if (++imagenum == 4) {
imagenum = 0;
} else {
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
Another point, that other users notice and I just report here in my answer.
You use the string:
imageCycle()
as the first argument of setTimeout, insted you should use just the function name.
timer = setTimeout(imageCycle, 1000);

Simple Javascript Gallery

So I'm trying to loop through this array and change an image source every few seconds. Right now I have an onload event calling a setTimeOut method which should change the image 5 seconds after the page has loaded I would think, but it is doing it instantly. What is the problem? Here is my code:
<html>
<head>
<title>Ad Rotaror</title>
<script type="text/javascript">
var i = 0;
var ads = new Array(4);
ads[0]='promo1.gif';
ads[1]='promo2.gif';
ads[2]='promo3.gif';
ads[3]='promo4.gif';
ads[4]='promo5.gif';
function change()
{
if(i > 4)
i = 0;
document.images[0].src = ads[i];
i++;
}
</script>
</head>
<body>
<img src="promo1.gif" onload="setInterval(change(), 5000)" />
</body>
</html>
Change 'change()' to 'change'. You are calling the function immediately.

Background Image/Color Changing

As part of my website projects, I would like to add a script, javascript or whatever, that changes the background image, but the problem is, I'm don't know how to program with Java. I only know Lua, HTML, & CSS.
The reason for that is because I'd like the background image to change after 5 seconds (fades into another image) and then again to another. A loop.
I have found something but it's said that it doesn't work:
<script language="JavaScript">
var Rollpic1 = "1.jpg";
var Rollpic2 = "2.jpg";
var Rollpic3 = "3.jpg";
var PicNumber=1;
var NumberOfPictures=3;
var HowLongBetweenPic=5;
function SwitchPic(counter){
if(counter < HowLongBetweenPic){
counter++;
document.roll.src = eval("Rollpic" + PicNumber);
CallSwitchPic=window.setTimeout("SwitchPic("+counter+")",1500);
}
else{
if(PicNumber < NumberOfPictures){
PicNumber++;
SwitchPic(0);
}
else{
PicNumber=1;
SwitchPic(0);
}
}
}
</script>
<body onload="SwitchPic(0)">
<img src="1.jpg" height="300" width="400" border="0" name="roll">
This will do it:
<script>
document.body.style.backgroundImage="url('path/to/background.png')";
</script>
Or if you want it to happen when you click something:
<script>
function change() {
document.body.style.backgroundImage="url('path/to/background.png')";
}
</script>
<input type="button" onclick="change()" value="Change it" />
To have some code loop on a timer:
<script>
function timedCount() {
// some code here
setTimeout("timedCount()",1000); //1000 milliseconds
}
</script>
Run that function ^ somehow (like with the onclick hander of a button as shown above) and it will loop forever, executing the function every 1000 ms
By the way, Java has nothing to do with Javascript. They're completely separate and are very different.
You can use CSS with Javascript to accomplish this easily like this:
<style>
.myImageClass { background-image: url(images/header.jpg); }
.extraClass { background-image: url(images/extra.jpg); }
</style>
<script type="text/javascript">
function changeMyBackground(elementID, myClassName = 'myImageClass'){
document.getElementById(elementID).className=myClassName;
}
// Change BG of element with id bgImage with the default class 'myImageClass'
changeMyBackground('bgImage');
// or change the bg of the element with id bgImage using a custom class.
changeMyBackground('bgImage', 'extraClass');
</script>
Define an ID to the element like this:
<body id="bgImage">
CONTENT
</body>
Is there a reason your not setting the background image in CSS?
Using jQuery is very easy, for example if you wanted to set a background on the body
$("body").css("background","url('images/bg.png')");
And don't forget to include jQuery in your header by:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
Maybe this will do:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var imageIndex = 0;
var imagesArray = new Array();
//Set Images
imagesArray[0] = "images/one.png";
imagesArray[1] = "images/two.png";
imagesArray[2] = "images/three.png";
function changeBackground(){
$("body").css("background","url('"+ imagesArray[imageIndex] +"')");
imageIndex++;
if (imageIndex > imageArray.length)
imageIndex = 0;
}
$(document).ready(function() {
setInterval("changeBackground()",5000);
});
</script>
</head>
To achieve a fade out transition to a new image you are better using an image tag . Inserting the new image with a lower z-index than the old image so it sits behind it. Next you fade out the old image and update the z-index of the new image.
I would recommend using JQuery cycle plugin (http://jquery.malsup.com/cycle/) because it will be easier for you to follow. Your code would therefore be:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src=”jquery.cycle.all.js” type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function() {
$(‘.pics’).cycle({
fx: ‘fade’,
speed: 5000
});
});
</script>
</head>
<body>
<div class=”pics”>
<img src=”image/one.png” />
<img src=”image/two.png” />
<img src=”image/three.png” />
</div>
</body>
</html>

Categories

Resources