When I click the "change lights" button I have to click it twice for the picture to change. What could be going wrong? Any ideas?
Here is my HTML:
<p>Click the button to change to the next light.</p>
<img id="starting_light" src="green.jpg">
<button type="button" onclick="nextLightClick()">Change</button>
And my JavaScript:
var gyr = new Array("green.jpg","yellow.jpg","red.jpg");
var index = 0;
var gyrLen = gyr.length;
function nextLightClick() {
if (index == gyrLen)
index = 0;
var image = document.getElementById('starting_light');
image.src = gyr[index];
index++;
}
I suspect the main problem to be in the JavaScript because once I started messing around with the variables the issue was introduced.
The first time this runs, the image is green.
It then sets the image to gyr[0], the green image, then index is incremented.
You can either increment the index before setting the image, or reorder the array to have green be last.
The first time you click the button, index is equal to 0, so nextLightClick() is setting image.src to "green.jpg", which is the same (assuming "1green.jpg" is a typo) as the starting image.
The solution is to move index++ to the first line of nextLightClick().
Your index is still 0 on the first time you enter the function and set the image.
Move the index++; to the start of the function, or initialize the index to value 1.
var index = 1;
If you want to initialize the index to 1, then you should rename the variable to something like nextIndex.
I don't think it is the case. Your code is working correctly. Your first image is green and the first time you click you are replacing it with the first image, that's the reason you don't see any difference.
You might consider doing it as:
var gyr = new Array("http://i.imgur.com/eucAMTA.jpg", "http://is2.mzstatic.com/image/thumb/Purple122/v4/be/9a/f0/be9af074-90f2-5894-99a0-17460783db6c/source/1200x630bf.jpg", "https://i0.wp.com/fusion.net/wp-content/uploads/2016/05/RED.jpg?resize=1600%2C900&quality=80&strip=all");
var index = 0;
var gyrLen = gyr.length;
function nextLightClick() {
index++;
// alert("hello" + index);
if (index == gyrLen)
index = 0;
var image = document.getElementById('starting_light');
image.src = gyr[index];
}
img {
width: 200px;
height: 200px;
}
p>Click the button to change to the next light.</p>
<img id="starting_light" src="http://i.imgur.com/eucAMTA.jpg">
<button type="button" onclick="nextLightClick()">Change</button>
Ah I seem to have found the answer thanks to Zac and American the problem was that index should have been at the first line of 'nexlightclick'
Fixed script below:
<p>Click the button to change to the next light.</p>
<img id="starting_light" src="green.jpg">
<button type="button" onclick="nextLightClick()">Change lights</button>
<script>
var gyr = new Array("green.jpg","yellow.jpg","red.jpg");
var index = 0;
var gyrLen = gyr.length;
function nextLightClick() {
index++;
if (index == gyrLen)
index = 0;
var image = document.getElementById('starting_light');
image.src = gyr[index];
}
</script>
</body>
</html>
There is a little problem with index update logic. You must evaluate its value and if it's less than gry.length add one else reinitialize to 0.
The inside script code:
var gyr = new Array("green.jpg","yellow.jpg","red.jpg");
var index = 0;
function nextLightClick() {
index = index + 1 < gyr.length ? index + 1 : 0;
document.getElementById('starting_light').alt = gyr[index];
}
Related
i'm trying to change images based on the user pressing the next button but that isn't happening
var my_image = document.getElementById(main_image);
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 1;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
<img src="https://www.w3schools.com/jsref/klematis.jpg" id ="main_image">
<button onclick="change_image()"> next </button>
document.getElementById() needs to have a string passed into it. If main_image is an element, and not a string, this could be your issue.
Looks like your array index is set wrong
There are 2 problems in your code:
1- getElementByID expects a string. By not putting quote marks around "main_image" javascript thinks main_image is a variable name, not a value.
2- your array only has one element, so it's position is 0, not 1.
Below your code is working:
var my_image = document.getElementById("main_image");
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 0;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
<img src="https://www.w3schools.com/jsref/klematis.jpg" id ="main_image">
<button onclick="change_image()"> next </button>
Alternatively you can querySelector.
Secondly instead of using onClick in the button use addEventListener.
`
let my_image = document.querySelector("#main_image");
let nextBtn = document.querySelector("button")
let image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
let image_index = 0;
const change_image =() => {
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
nextBtn.addEventListener("click", change_image)
`
The answer has been given, I'm only improving on the syntax
Pass a string into the document.getElementById(). I hope this works for you.
Here is the code I have so far, and all it can do is display the first image however once the button is pressed the image doesn't change and I'm not sure what to do?
var index = 0;
var ImageList = ["Images\sad.png", "Images\happy.png"];
function changeImage() {
index = index + 1;
if (index == ImageList.length) {
index = 0;
'at this point it is supposed to change the image'
}
var image1 = document.getElementById("myImage");
image1.src = ImageList[index];
}
<button onclick="changeImage()">Change emotions</button>
<img id="myImage" src="Images\happy.png" style="width:200px">
You should set a global variable containing the reference to the element instead of setting it with every function call.
Another thing - your index was initially set to 0 and the default img was the image on the second position in array, with index 1, so with the first function call nothing was happening because the src wasn't changed.
var index = 0;
var ImageList = ["http://placehold.it/350x150", "http://placehold.it/150x150"];
var image1 = document.getElementById("myImage");
function changeImage() {
image1.src = ImageList[index];
if (index < ImageList.length-1) {
index = index + 1;
} else {
index = 0;
}
}
<img id="myImage" src="http://placehold.it/150x150" style="width:200px">
<button onclick="changeImage()">Change emotions</button>
you must escape your backslash in file paths.
var ImageList = ["Images\\sad.png","Images\\happy.png"];
your code with changes:
var index=0;
var ImageList = ["Images\\sad.png","Images\\happy.png"];
function changeImage(){
index=index+1;
if(index==ImageList.length){
index=0; 'at this point it is supposed to change the image'
}
var image1= document.getElementById("myImage");
image1.src= ImageList[index];
}
<button onclick = "changeImage()">Change emotions</button>
<img id="myImage" src="Images\happy.png" style="width:200px">
Not sure if you had this in the code all along or if you added it for this post, but wrote a comment that was invalid syntax:
'at this point it is supposed to change the image'
Comments should be like this:
// at this point it is supposed to change the image
Your slashes in your image paths should be forward and not backslashes as well.
See comments inline with the code for other corrections and explanation:
var index = 0;
// Paths should always use forward-slashes, not back-slashes
var ImageList = ["http://images.clipartpanda.com/apple-clipart-apple5.png",
"http://web.utk.edu/~gduscher/images/orange.jpg"];
// Get your reference to the image element outside of the function
// so you don't have to keep getting it every time the button is clicked.
var image1 = document.getElementById("myImage");
function changeImage() {
// Increment the index counter by 1
index = index + 1; // could just write: index++
// If the index has gone too high, reset it to zero
if(index == ImageList.length){
index=0; // You wrote your comment wrong: 'at this point it is supposed to change the image'
}
// Set the source of the image
image1.src= ImageList[index];
}
img { width: 50px; }
<button onclick = "changeImage()">Change emotions</button>
<img id="myImage" src="http://images.clipartpanda.com/apple-clipart-apple5.png" style="width:200px">
Instead of an if statement for toggling between 0 and 1 (assuming you're only going to have two images), you can use a ternary operator:
(index === 0) ? (index = 1) : (index = 0);
The issue is in the backslashes. What do you use them for?
In javascript the backslashes in strings are for special characters, so when you change img.src = list[index] it will change from Images\happy to Imageshappy
your code working
I'm supposing your images are in a folder called 'Images'.
var index=0;
var ImageList = ["Images/happy.png", "Images/sad.png"];
function changeImage(){
index=index+1;
if(index==ImageList.length){
index=0;
}
var image1= document.getElementById("myImage");
console.log(image1);
image1.src= ImageList[index];
console.log(image1);
}
<button onclick = "changeImage()">Change emotions</button>
<img id="myImage" src="Images/happy.png" style="width:200px">
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3- Traffic Light Sequence </h1>
<img id="light" src="./assets/red.png" height="205" width="95">
<button type="button" onclick="changeLights()">Change Lights</button>
<script>
var colours = ["./assets/red.png","./assets/red_and_amber.png", "./assets/green.png","./assets/amber.png" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == colours.length)
index = 0;
var image = document.getElementById('light');
image.src = colours[index];
}
</script>
</body>
</html>
this code is to show a traffic light sequence. First red, then red and amber, then green, then back to amber, and then back to red. I'm unsure of what the function exactly does line by line.
Index is the number to use with colours array.
Ex:colours[0] is the first colour in the array;
Then the index +=1,now index==1;
The second time:
colours[1] is the second,etc
I'm unsure of what the function exactly does line by line.
Here is a line-by-line explanation:
var colours = [
"./assets/red.png",
"./assets/red_and_amber.png",
"./assets/green.png",
"./assets/amber.png"
];
Sets up an array called colours, containing 4 values.
var index = 0;
Sets up a variable called index.
function changeLights() {
Sets up a function called changeLights.
index = index + 1;
Increases the value of index by 1.
if (index === colours.length) {
Checks if the value of index is equal to the number of values in the colours array.
index = 0;
Resets index to 0.
var image = document.getElementById('light');
Finds <img id="light" ... /> in the markup and assigns it to a variable called image.
image.src = colours[index];
Rests the src value of image to the index-th value of the colours array.
I got a problem while writung a code for a Heatmap based on link clicks.
I have a Page with different articel teasers. When i click the link the artical itself opensup. Now i want to track in real time how often which articel is clicked so i can decide which articel is relevant to users and place it like on the first articel space and so on.
Therefor i wrote a function which tracks the clicks with a counter and show them in the div.
Now my problem is. That i cant write like 20 functions for counters and 20 for resets. I want to have one function which can decide which articel was clicked and add +1 to the counter of the link.
My Code for the counter and the reset + the link text gets red after more than 5 clicks.
var count1 = 0;
function heatmap(id) {
if(id==1){
count1++;
document.getElementById("count1").innerHTML = count1;
}
if(count1>=5){
document.getElementById("link1").style.color = "red";
}
}
function reset(id){
if(id==1){
count1=0;
document.getElementById("count1").innerHTML = 0;
}
}
My html code so far
<div style="text-align:center; font-size:20px; font-family: arial;">
<div id="link1" onclick="heatmap(1)">This is the first Link</div><br>
<div id="count1">0</div><br>
<button onclick="reset(1)">RESET</button>
<button onclick="save(1)">SAVE</button>
</div>
Now my main problem is that i only want one function for all the link tracking.
Is there a possibiblity to write the code in a way the variables are dynamicly so that the function can decide which link was clicked.
for example something like:
var count + ID = 0;
function heatmap(ID) {
count + ID ++;
document.getElementById("count" + ID).innerHTML = count+ID;
}
if(count + ID >=5){
document.getElementById("link + ID").style.color = "red";
}
}
function reset(id){
count + ID =0;
document.getElementById("count + ID").innerHTML = 0;
}
}
I already searched this homepage and did some google searches but all i found was working with arrays or lists. But i think this wouldnt realy work for me since i want to give my function an ID and later add this id to the varibale name like count + ID = count | count + ID = count2 same with the document.getElementById("count" + ID).innerHTML = count+ID; = document.getElementById("count1").innerHTML = count1;
As you can see the link got a onclick="heatmap(ID)" this ID will be added to every articel Link and will go from the first articel with 1 to the last articel with like 20.
If i change an Articel the counter will be resetet and the ID will be changed to its position. So there will always be a identifier with the ID which can be used for the counter.
You could loop through all articles and store a counter on each element which you update or reset once the specific button inside the article was clicked:
var articles = document.querySelectorAll('article');
for(var i=0; i < articles.length; i++) {
articles[i].querySelector('.save').addEventListener('click', updateCounter);
articles[i].querySelector('.reset').addEventListener('click', resetCounter);
articles[i]['counter'] = 0;
}
function updateCounter(ev) {
var article = ev.target.parentNode;
article.counter++;
article.querySelector('.counter').innerHTML = article.counter;
/* Some server synchronisation should go here */
}
function resetCounter(ev) {
var article = ev.target.parentNode;
article.counter = 0;
article.querySelector('.counter').innerHTML = article.counter;
/* Some server synchronisation should go here */
}
DEMO
But to permanently store the counters you have to synchronize your results with a server, respectively a database.
If you just want to use one function you could realize it like this:
var articles = document.querySelectorAll('article');
for(var i=0; i < articles.length; i++) {
articles[i].querySelector('.save').addEventListener('click', checkCounter);
articles[i].querySelector('.reset').addEventListener('click', checkCounter);
articles[i]['counter'] = 0;
}
function checkCounter(ev) {
var article = ev.target.parentNode,
button = ev.target;
if(button.classList[0] === 'save') {
article.counter++;
} else if(button.classList[0] === 'reset') {
article.counter = 0;
}
article.querySelector('.counter').innerHTML = article.counter;
}
DEMO
I have a <div> and i want to add images into it. The number of images will vary randomly.
here is what i am trying to do
$(document).ready(function () {
var img = document.getElementById("img");
$('#button').click(function () {
var randomnumber = Math.floor(Math.random() * 11) + 1;
for (var i = 1; i < = randomnumber; i++) {
$(this).append(img);
}
});
});
But it is not working. Please help
here is my code JSFiddle
You should probably use clone as simon suggests, or you can create new images:
function getImage(){
var img = new Image();
img.src = "http://cdn.acidcow.com/pics/20110830/lolcats_ever_13.jpg"
img.width = 200;
return img;
}
var rand = Math.floor(Math.random() * 11) + 1,
imgContainer = $("#imgContainer"),
i;
$("#imgNo").text(rand);
for (i=0; i<rand; i++){
imgContainer.append(getImage());
}
fiddle
uhm, you aren't defining any new images. I am not sure from where you are getting your images. If you have differeny images, you can use the next loop. Besides that, the this points to the #button element. Not sure which item it is, but if it's an input button, then it won't work. you have to use a div or article or section ... as target.
$(document).ready(function () {
$('#button').click(function () {
// random number
var randomnumber = Math.floor(Math.random() * 11) + 1;
// insert images
for (var i = 1; i < = randomnumber; i++) {
// create a new img - element
var img = document.createElement('img');
// give it an id
img.attr("id","img_" + i);
// source, link
img.attr("src","your_URL_here");
// put newly created image in the div with id yourDivIdHere
$('#yourDivIdHere').append(img);
}
});
});
the id has to be unique, that's why i'm using the index of the for loop for the id of the newly created element. Having same id for multiple HTML elements can lead to issues.
#yourDivIdHere means the div with the id yourDivIdHere, like
<div id="yourDivIdHere"></div>
When you are re-using the button, simply clear the content by using $('#yourDivIdHere').empty() method if you don't want to see that old images are still there after clicking on the button.
You need to clone the image:
$(this).append( $(img).clone() );
Your way always puts the same image (only one instance!) inside of div random amount of times. So in the end it is only one image.
If you clone it every time then you will have N amount of images
You are getting elements by id, so appended element is always the same element with id="img". Read about jQuery find() to find all elements.