I had a look here and here for my answer but found that the code was far too long for such a simple process.
Below, my code shows a basic Image Changer by having the 'image' changed to the different .jpg's in an array, located in the same file.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
</script>
</body>
</html>
In theory, because I've embedded the script within the HTML it should work like a dream, but the image seems to get stuck on the yellow light. Is there a repeat button click phase I'm missing?
Thanks.
There is no need to use a loop. You can get reference to the button using document.getElementsByClassName("change-image")[0];. Then you can add an event lister to trigger on each button click.
Each time a user clicks you iterate through the array by one.
You could look at doing something like this:
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click',function() {
if(index === imageSources.length ) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
Here is the complete code, which works. If you inspect the img element you will see that it updates.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class="change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
</script>
</body>
</html>
Funny implementation -))
document.getElementById("changer").addEventListener("click", function(){
var i = document.getElementById("source");
var images = [
"http://lorempixel.com/400/200/sports",
"http://lorempixel.com/400/200/animals",
"http://lorempixel.com/400/200/nature"
];
var ord = parseInt(i.dataset.order);
nextImage = function(prev) {
return (prev+1 >= images.length ? (prev + 1)%images.length : prev+1);
}
document.getElementById("source").src = images[nextImage(ord)];
i.dataset.order = ord + 1;
})
<img id="source" data-order="0" src="http://lorempixel.com/400/200/sports">
<button id="changer">change</button>
Related
Code is supposed to show next image when clicking on next arrow and previous image when clicked on previous arrow. It does not work though. (error occurs while assigning img.src=imgs[this.i]; it says Cannot set property 'src' of null
at collection.next) .
Javascript code :
var arr = new collection(['cake.png', 'image2.png', 'image3.png', 'image1.png']);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById('element')
this.i++;
if (this.i == imgs.length) {
this.i = 0;
}
img.src = imgs[this.i].src;
}
this.prev = function(element) {
var img = document.getElementById('element');
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i].src;
}
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
Not using jquery. I do not have enough experience in js either. Thank you for your time
You had three mistakes:
You referenced the images as img.src = imgs[this.i].src; and you just had an array of strings, not an array of objects with a src property. img.src = imgs[this.i]; is the correct way to get the URL.
You used
var img = document.getElementById('element');
when you should have used
var img = document.getElementById(element);
element is an argument coming from your onclick event. It holds the id of your image that you should be using. "element" is just a string. You try to find an element with id equal to element which doesn't exist.
Edit: You should also use < and > to represent < and >. Otherwise your HTML might get screwed up. More on that here.
var arr = new collection(['http://images.math.cnrs.fr/IMG/png/section8-image.png', 'https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg', "http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"]);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById(element);
this.i++;
if (this.i >= imgs.length) {
this.i = 0;
}
img.src = imgs[this.i];
};
this.prev = function(element) {
var img = document.getElementById(element);
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i];
};
this.next("mainImg"); // to initialize with some image
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
This is how I'd personally do it:
var myCollection = new Collection([
"http://images.math.cnrs.fr/IMG/png/section8-image.png",
"https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg",
"http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"
], "mainImg");
document.getElementById("next_btn").onclick = function() {
myCollection.next();
};
document.getElementById("prev_btn").onclick = function() {
myCollection.prev();
}
function Collection(urls, imgID) {
var imgElem = document.getElementById(imgID);
var index = 0;
this.selectImage = function() {
imgElem.src = urls[index];
};
this.next = function() {
if (++index >= urls.length) {
index = 0;
}
this.selectImage();
};
this.prev = function(element) {
if (--index < 0) {
index = urls.length - 1;
}
this.selectImage();
};
// initialize
this.selectImage();
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input id="next_btn" type='button' value='<' />
<img id='mainImg'>
<input id="prev_btn" type='button' value='>' />
</body>
</html>
Why sending string into arr.next('mainImg') function ?
your img element always have the same id, only change src.
and document.getElementById(element) is also the same img element.
html: <img id='mainImg' src="cake.png">
js: document.getElementById('mainImg')
consider img element as a container, and id is it's identifiler.
var start_pos = 0;
var img_count = document.getElementsByClassName('icons').length - 1;
var changeImg = function(direction){
pos = start_pos = (direction == "next")? (start_pos == img_count)? 0 : start_pos+1 : (start_pos == 0)? img_count : start_pos-1;
console.log(pos)
}
document.getElementById('left').onclick = function(){ changeImg("previous"); }
document.getElementById('right').onclick = function(){ changeImg("next"); }
I have make a traffic light system using javascript and used the setInterval to make it go by itself, however how can i make the timings different? for example i would like the red light and green light to stay on longer then amber and red amber.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<p>This is my very first JavaScript task</p>
<img id="traffic" src="red.png">
<button type="button" onclick="dosomething()">something magical will happen if you press me</button>
<script>
var list = ["red.png", "redamber.png", "green.png", "amber.png"];
var index = 0;
var timer = setInterval(dosomething, 3000)
function dosomething(){
index = index + 1;
if (index == list.length) index = 0
var image = document.getElementById('traffic');
image.src=list[index];
}
</script>
</body>
</html>
Here is an example using a weighted-time similar to what I was explaining in my comment. I don't have your images so I replaced them with text.
function changeColors(){
if (index >= list.length) index = 0;
let item = list[index];
if (!item.countdown) item.countdown = item.weight - 1;
else item.countdown = item.countdown - 1;
var image = document.getElementById('traffic');
image.innerHTML=list[index].color+'-'+item.countdown;
if (item.countdown == 0) index = index + 1;
}
var list = [
{color:"red.png", weight:1},
{color:"redamber.png", weight:3},
{color:"green.png", weight:2},
{color:"amber.png", weight:1}
];
var index = 0;
let btnChangeColors = document.getElementById('btnChangeColors');
btnChangeColors.onclick = function() {
var timer = setInterval(changeColors, 1000);
};
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<div id="traffic"/>
<button type="button" id="btnChangeColors">Start Traffic Light</button>
This is my code, it only outputs the original red image and i don't understand how i'm supposed to make the code able to loop. Could someone help as I need this code desperately?
<!DOCTYPE html>
<html>
<head>
<h1> The traffic script</h1>
<script>
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
window.onload = changelights;
</script>
</head>
<body>
<img id="red" src="H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg">
</body>
</html>
Use SetInterval - this is not a loop like a for loop, etc. It is simply a block of code that will get triggered every x miliseconds.
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
setInterval(function(){changeLights()}, 4000);
This will call changeLights every 4 seconds. Also - be careful asking GCSE questions here especially the course work.
JavaScript has a built-in interval method, which can be used as a loop in this case.
var backgroundInterval = setInterval(function() {
changeLights();
if(index == (list.length - 1)) {
clearInterval(backgroundInterval); // stop the loop when it hits last image
}
}, 4000); // every 4000 ms, or 4s
Ok so we have a simple user info editing page.I want to create a toggle button which swaps profile picture border-radius from 0 to 25 and backwards.But the 2nd part doesnt work.I created if to check if the boarder radius is 25 already so it will make it 0, but it does not work.Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>
<button onclick="changeShape()">ChangeShape</button>
<button onclick="uploadImage()">Upload Image</button>
</body>
<script>
var images = [ 'profile1.png', 'profile2.png','profile3.png'];
var index = 0;
var array_length = 3;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage(){
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % array_length;
img.src = images[index];
}
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "25px";
if(shape.style.borderRadius == 25){
var shape2 = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "0px";
}
}
function uploadImage() {
images.push("profile4.png");
array_length++;
}
</script>
</html>
Any ideas why it doesnt work?
You are uselessly assigning variables in your function by the looks of it.
There is no need to declare shape2. Just declare shape once and then use that to check. Also make sure to check shape.style.borderRadius against a string like "25px" as that will be returned.
Try something like this:
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0];
if(shape.style.borderRadius == "25px"){
shape.style.borderRadius = "0px";
}else{
shape.style.borderRadius = "25px";
}
}
My HTML page has an image with id img. The idea is that by clicking first, previous, or next, the user can navigate through a set of images. How do I do this using JavaScript?
This should be a good start for you:
<script>
var imgs = ["img1.png","img2.png","img3.png"]; // copy images to the same dir
var index = 0;
</script>
<img src="img1.png" onclick="this.src=imgs[++index%imgs.length]"/>
click the image to slide.
If you need buttons, see this example:
<img id="clicker" src="img1.png"/>
Prev
Next
First
Last
<script>
var imgs = ["img1.png","img2.png","img3.png"];
var index = 0;
var clicker = document.getElementById("clicker");
function prev() { clicker.src = imgs[--index%imgs.length]; }
function next() { clicker.src = imgs[++index%imgs.length]; }
function first() { clicker.src = imgs[index=0]; }
function last() { clicker.src = imgs[index=imgs.length-1]; }
</script>
The return false means that default action on click (follow the link) is supressed. Javascript can access elements i.e. using id (see clicker here). Once you get comfortable with this and you start to solve browser compatibility problems, it is good idea to continue with jQuery (as the other suggests), MooTools or other framework.
Use jQuery!
var myImg = $("#myimg");
$("#next").click(function(){
var id = myImg.attr("data-id") + 1;
myImg.attr("src", "image"+id+".jpg");
});
$("#prev").click(function(){
var id = myImg.attr("data-id") -1;
myImg.attr("src", "image"+id+".jpg");
});
HTML:
<img id="myimg" src="image1.jpg" data-id="1">
Next<br>
Previous<br>
This is a very dummy example. There are numerous slideshow plugins out there!
No need jQuery:
<script type='text/javascript'>
window.onload = function() {
var imageSrcs= ['1.jpeg', '2.jpg', '3.jpg'];
var index = 0;
var image = document.getElementById('img');
var previous = document.getElementById('previous');
previous.onclick = function() {
index -= 1;
if(index < 0) index = imageSrcs.length - 1;
image.src = imageSrcs[index];
}
var next = document.getElementById('next');
next.onclick = function() {
index += 1;
if(index == imageSrcs.length) index = 0;
image.src = imageSrcs[index];
}
}
</script>
And html:
<img src='1.jpeg' id='img'>
<div>
<span id='previous'>Previous</span>
<span id='next'>Next</span>
</div>
You do not need a library for this. Something like this will change the image url, where "theImg" is the id of the image:
document.getElementById("theImg").src = "newUrl.png";
To do it without explicit ids, this will change the url where i is the index of the image:
document.getElementsByTagName("img")[i].src = "newUrl.png";
Try something like this (untested):
LOAD JQUERY:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
JAVASCRIPT:
<script type='text/javascript'>
var lst_src = ['img1.jpg', 'img2.png', 'img3.gif'];
$('a', '#nav').click(function(e) {
e.preventDefault();
var src_current = $('#img').attr('src');
var index = lst_src.indexOf(src_current);
var len = lst_src.length;
var action = $(this).attr('class');
switch ($action) {
case 'previous' : var i = index - 1;
if (i < 0) src_current = lst_src[len + i];
else src_current = lst_src[i];
break;
case 'next' : var i = index + 1;
if (i > len) src_current = lst_src[i - len];
else src_current = lst_src[i];
break;
case 'first' : src_current = lst_src[0];
break;
case 'last' : src_current = lst_src[len - 1];
break;
}
$('#img').attr('src', src_current);
});
</script>
HTML: Use the class of a link to denote the required action:
<img id='img' src='img1.jpg'>
<p id='nav'>
<a href='' class='first'>←←First</a>
<a href='' class='previous'>←Previous</a>
<a href='' class='next'>Next→</a>
<a href='' class='last'>Last→$rarr;</a>
</p>