I can't get my image slideshow to work using JavaScript - javascript

I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.

picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.

You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {

have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>

Related

JavaScript: Toggling Between 2 Images Not Working, Using setInterval

New to JS. I am trying to toggle between showing two images, dragon.svg, and dragon1.svg, every 1 second starting on page load, and running indefinitely. However, my image only changes once, and then keeps running every second but not following the rules of my if/else statement.
My suspicion is that the function is not changing the value of a global variable called dragonDiv each time it runs, so each time it runs, it is using the original value of the dragonDiv variable.
On the HTML, I have a div with the image inside, like this:
<body onload="changeDragon();">
<div id="dragonarea">
<img src="images/dragon.svg"/>
</div>
</body>
And then I have this JS, which should change the image to dragon1.svg if it is currently dragon.svg, and vice versa, every 1 second.
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonDiv = document.getElementById('dragonarea');
console.log(dragonDiv.innerHTML); // Correctly logs <img src="images/dragon.svg"/>
function dragonColorChange() {
if (dragonDiv.innerHTML = '<img src="images/dragon.svg">') {
dragonDiv.innerHTML = '<img src="images/dragon1.svg">';
console.log(dragonDiv.innerHTML) // Correctly logs <img src="images/dragon1.svg"/>
} else {
dragonDiv.innerHTML = '<img src="images/dragon.svg">';
console.log(dragonDiv.innerHTML) // Never makes it to this point
}
}
As noted above, the console log tells me that it is correctly changing the image the first time, but after that, it seems like it is again taking the original value of dragonDiv (with the dragon.svg image) and running the function on that innerHTML again (so changing it to dragon1.svg again), rather than updating the innerHTML after running the function once as I'm telling it to do and forcing it to the else statement.
I tried putting the dragonDiv variable inside the dragonColorChange function as well as outside as a global variable. I tried using document.getElementById('dragonarea').src instead of replacing the entire innerHTML of the div tag. I tried using === instead of just =. I tried various other things for about 4 hours and I can't figure out how to get it to keep looping through the if/else statements.
Any mistakes I'm making in my code?
Apart from the typo (= is assignment, == or == is comparison) you have several improvements you can make
Use addEventListener
Change src, not innerHTML, waste of DOM rendering
I suggest a data-attribute
let changeInterval;
let dragonImage;
window.addEventListener("load", function() {
dragonImage = document.getElementById("dragonImage");
changeInterval = setInterval(dragonColorChange, 1000);
})
function dragonColorChange() {
const toggle = dragonImage.dataset.toggle
const src = toggle === "0" ? "images/dragon1.svg" : "images/dragon.svg";
dragonImage.src = src;
dragonImage.dataset.toggle = toggle === "0" ? "1" : "0";
}
<div id="dragonarea">
<img id="dragonImage" data-toggle="0" src="images/dragon.svg" />
</div>
Typo I guess, use === or == for comparison.
Also, onload function on body had different quotes [”] (when I copied and pasted on jsfiddle, it didn't work) instead of ["]
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonDiv = document.getElementById('dragonarea');
/* console.log(dragonDiv.innerHTML); // Correctly logs <img src="images/dragon.svg"/> */
function dragonColorChange() {
if (dragonDiv.innerHTML === '<img src="images/dragon.svg">') {
dragonDiv.innerHTML = '<img src="images/dragon1.svg">';
console.log(dragonDiv.innerHTML) // Correctly logs <img src="images/dragon1.svg"/>
} else {
dragonDiv.innerHTML = '<img src="images/dragon.svg">';
console.log(dragonDiv.innerHTML) // Never makes it to this point
}
}
<body onload="changeDragon();">
<div id="dragonarea">
<img src="images/dragon.svg" />
</div>
</body>
Here I compare and change the image.src directly, instead of the div's innerHTML, as others have suggested already.
HTML:
<body onload="changeDragon();">
<div id="dragonarea">
<img id="dragon-image" src="images/dragon.svg"/>
</div>
</body>
JavaScript:
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonImage = document.getElementById('dragon-image');
function dragonColorChange() {
if (dragonImage.src === 'images/dragon.svg') {
dragonImage.src = 'images/dragon1.svg';
} else {
dragonImage.src = 'images/dragon.svg';
}
}
As others have said you need the ===.
Here's one way to do it and keep the variable scoped to the function. I'm using .getAttribute("src") instead of just .src since it gets the relative url path.
Note that dragonColorChange isn't being passed into setInterval. It's the function returned by calling dragonColorChange.
const changeDragon = function () {
changeInterval = setInterval(dragonColorChange(), 1000);
};
function dragonColorChange() {
let dragonImg = document.querySelector('#dragonarea img');
return function () {
dragonImg.src = dragonImg.getAttribute("src") === "images/dragon.svg" ? "images/dragon1.svg" : "images/dragon.svg";
}
}
In the if condition there is a typo. Instead of comparison with == or === there is assignment operator which will assign rather than compare. Try changing that to comparison.

Javascript image swap sequence

As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>
in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps
I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>
Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:

open if bracket in javascript

I'm trying to execute a HTML code if there is variable in JS, is there something like in PHP, where you can use
<?php
if ($variable == True) { ?>
<img src="image.jpg">
<?php } else { ?>
<img src="image2.jpg">
<?php } ?>
so in JS
<script>
if (variable == true) {
</script>
<img src="image.jpg">
<script>
} else {
</script>
<img src="image2.jpg">
<script>
}
</script>
or it has to been done like this
<script>
if (variable == true) {
$("#element").prepend("<img src='image.jpg'>");
} else {
$("#element").prepend("<img src='image2.jpg'>");
};
</script>
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
Thank you :)
Well last one is correct one but you can simplify it:
var src = variable === true ? "image" : "imgage2";
$("#element").prepend('<img src="'+ src +'.jpg">');
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
That could be because of dynamically element's creation, you can sort it out with event delegation.
With jQuery:
$('#element').on('click', 'img', function(e){
// put code here
});
With javascript it is little bit different, .querySelectorAll() returns a collection with is array like object, so iteration needs to be there, Collection.forEach(cb) can be used to bind the event:
var imgs = document.querySelectorAll('#element img');
Array.forEach.call(imgs, function(img){
img.addEventListener('click', function(){
// put code here
});
});
And with js all the events are delegated events.
I assume that you want to check if your variable is boolean and you want to check if it is true.
Also i assume that you have several images and you want to prepend new one to them, then you could do:
Create hidden div on the page, Something like this:
<div id="htmlToDomCreator" style="position: absolute; top: 0; left: 0; width: 1px; height: 1px; visibility: hidden;" >
</div>
Inside your javascript code do something like this:
<script>
var htmlToDomCreator = document.getElementById('htmlToDomCreator');
var yourElement = document.getElementById('element');
var htmlTag = "";
if (variable == true) {
htmlTag ="<img src='image.jpg'>";
} else {
htmlTag ="<img src='image2.jpg'>";
}
htmlToDomCreator.innerHTML = htmlTag;
var myImgTag = htmlToDomCreator.firstChild;
if(yourElement.firstChild){
yourElement.insertBefore(myImgTag, yourElement.firstChild);
}else{
yourElement.appendChild(myImgTag);
}
myImgTag.onclick = function() {
// do click stuff here
};
</script>
The idea is that whether you use innerHTML or prepending string with jquery,
you have to take whole innerHTML, prepend string to it and then reinsert
whole content again. As you undoubtedly can see, this "kills" all handlers
added from javascript and you have to reattach them again.
To avoid this, we create dom from string "somewhere else" and then prepend it as a dom child element.
Try this:
<script>
if (variable == true) {
$("#element").attr('src', 'image.jpg');
} else {
$("#element").attr('src', 'image2.jpg');
};
</script>
Comment:This will only change the picture attribute, not the entire <img... /> element. So, events attached to the img element will be preserved.

Javascript cycling text

I used it and it worked perfect... and now I don't understand why it stopped working... I'm not a programmer so if I deleted something by mistake it's hars for me to find it... I did look everything... everything seems fine to me... please can you tell me why I now have UNDEFINED error ?
I have this in my heading :
<script type="text/javascript" src="js/textCycle.js"></script>
and this in my body tag :
<body onload="changeText()">
and this is where the script should be :
<table border = 0><tr><td style="width:300px;" height="100px"> <!-- Change the height in order to determine width of quotes -->
<div id="change"></div></td></tr></table>
and this is my JS :
var quotes=new Array(5);
var i = 0;
var authors=new Array(5);
//Load Quotes into array
quotes[0]="\"Temoignage #1\"";authors[0]="Client #1";
quotes[1]="\"Temoignage #2\"";authors[1]="Client #2";
quotes[2]="\"Temoignage #3\"";authors[2]="Client #3";
quotes[3]="\"Temoignage #4\"";authors[3]="Client #4";
quotes[4]="\"Temoignage #5\"";authors[4]="Client #5";
//Call the changeText() function every 5000 miliseconds
setInterval(changeText, 3000);
//Function that determine what quote and author to put in html.
function changeText(){
document.getElementById("change").innerHTML=(quotes[i] + '<p style="text-align: right"><i>' + authors[i] + '</i></p>');
if(i == 4)
i = 0;
else
i++;
}
I changed a few things in the JS and it was working... And suddently it stopped working after doing something (this is the something I can't remember!) and I'd like to know what is wrong with my code?
Thank you for your help!
It appears that there is another global i variable on your page, which is set to some arbitrarily high number bigger than the size of your quotes array, so it's undefined.
Rename i to something more descriptive like currentClientIndex and you should be good.

javascript random flashing words

Here's a fun little script I'm trying to make. Flash words from an array with random colors from another array. (I'm mostly thinking about having a moving bg type deal.)
I'm having problems with creating some sort of loop to cause the words to "flash/change" so far all it does is change on page reload.
*new*
Well I changed it so now it is just one function... and it WORKS!! but it seems that it uses the browsers memory or something and crashes.... oops... is there a clear memory or something for javascript that I should use??
<html>
<head>
<style>
body
{
color:black;
}
#quotes
{
}
</style>
</head>
<body>
<script type="text/javascript">
function showQuote()
{
pickWords =
[
"Hi!",
"Welcome!",
"Hello!"
]
var word22 = pickWords[Math.floor(Math.random()*pickWords.length)];
pickColors =
[
"#aa2233",
"#00cc44",
"#F342AA"
]
var Color22 = pickColors[Math.floor(Math.random()*pickColors.length)];
var Top22 = (Math.floor(Math.random()*800));
var Left22 = (Math.floor(Math.random()*800));
var style33 = '<h4 style="padding-bottom:0px; padding-top:'+Top22+'px; padding-left:'+Left22+'px; font-size: 2.3em; color:'+Color22+';">';
var style34 = '</h4>';
var finWord22 = style33 + word22 + style34;
var duration = 400;
document.getElementById("quotes").innerHTML=finWord22;
setInterval('showQuote()',duration);
}
onload = function()
{
showQuote();
}
</script>
<div id="quotes"></div>
</body>
You would need to 'pickword' inside the showQuote() function.
Right now, you are picking a word onload, and use that word on every timeout.
Wrap your whole code into a function and call that function on load.
function ShowQuote(){
//...
setTimeout(ShowQuote, duration);
}
ShowQuote();
You're calling setinterval in the function, where as you should use settimeout. That should help you out with the crashing :P

Categories

Resources