Javascript function continues a step longer than needed - javascript

I have a function that continues one step longer than needed. When the image (elefant.png) is clicked the image (scale1.png) is changed. There are 5 pictures and it works fine. Problem is that when the last picture is displayed, and I click (elefant.png) again it comes to an undefined picture? I don't understand why it doesn't just stop on the last picture (scale5.png)?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<link rel="stylesheet" href="style.css">
<body>
<div class="wrapper1">
<h2 id="title_text">Hey</h2>
<img src="image/scale1.png" id="getImage">
<img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">
</div>
<script type="text/javascript">
var counter = 0,
gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
imagefun = function () {
document.getElementById("getImage").src = gallery[counter];
counter++;
if (counter >= 4) {
document.getElementById("title_text").innerHTML = "New text!";
}
};
</script>
</body>
</html>
This might be an easy fix, but I am not good with javascript. I tried searching for an answer but I'm not sure what to even look for as I don't know what causes the issue?

I'm not exactly sure what your end result should be once you hit the end of your gallery array but as it stands it changes title_text to "New text!".
The problem with your code as it stands is you always increment counter and change the source getImage based on that integer. That doesn't stop once your counter hits 4.
I'd use the array length as a stopping point and only increment the counter variable up until that limit is hit. I would write something like this:
var counter = 0,
gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
imagefun = function () {
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "New text!";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
<div class="wrapper1">
<h2 id="title_text">Hey</h2>
<img src="image/scale1.png" id="getImage">
<img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">
</div>

You always run the function and change the image source, and only then check for counter's value. That's why it'll keep going and changing the source even when counter is bigger than 3.
A solution would be to change counter' s value conditionally:
if (counter < gallery.length - 1) {
counter++;
}

Related

Chrome returns error code 5 for increment click function

I've written some code in html and javascript and when I drag it into chrome to test it, I get error code 5 in return. I've tried everything that chrome itself recommends when this happens as well as trying with different code, which works. heres my code:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var x = 1
var total = 0
var increment = 1
setInterval(function(){ total + increment; }, 1000);
while (x = 1) {
$(document).ready(function(){
$("#id").click(function(){
$("h1").text(total + 1);
});
});
}
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>
keep in mind, I'm extremely new to both of these languages, so I'm learning as I go.
There are some issues in your code:
your while loop runs forever since x=1 will remain true (which is causing the error), furthermore x isn't changed in the loop
the function in setInterval is doing nothing since there is no assignment =
Anyway, you don't need the most stuff. It is enough to get the value of h1 and increment it directly. If the script tag is put before the closing body tag you don't need the $(document).ready-part. So the following is all javascript you need:
Working example:
$("#id").click(function() {
$("h1").text(parseInt($("h1").text()) + 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>0</h1>
<button id="id">??????????</button>
By the way, you don't need jQuery for that and can use plain javascript.
Working example:
document.getElementById('id').addEventListener('click', function() {
document.querySelector("h1").textContent = parseInt(document.querySelector("h1").textContent) + 1;
});
<h1>0</h1>
<button id="id">??????????</button>
You don't have to declare variable x at all. Also, you don't need while loop.
Your loop will go to infinity because condition while(x=1) will be always true.
I guess infinite while loop crashes your Chrome browser.
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var total = 0
$(document).ready(function() {
$("#id").click(function() {
total++;
$("h1").text(total);
});
});
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>

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:

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);

Javascript Sound Start/Stop and Image Change

I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>

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.

Categories

Resources