<!DOCTYPE html>
<html>
<head>
<script>
var trafficlights = ['redlight.png','yellowlight.png','greenlight.png'];
var num = 1
function lightsequence() {
document.getElementById('light').src = trafficlights[num];
num = num + 1;
}
</script>
</head>
<body>
<img id="light" src="redlight.png">
<button onclick="lightsequence()">Change Lights</button>
</body>
</html>
I have written that piece of code and the images change in order one by one each time I click the button but I cannot think of how to reverse the order if I keep clicking, i.e. traffic lights red yellow green yellow red etc. each time I click. I am unfamiliar with jQuery so would like to not use them ideally but if someone can explain it fully with jQuery in working it will have to do.
Modulo operator is very convenient in such cases:
document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
Here is a demo:
var trafficlights = [
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png',
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png',
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Green.png'
];
var num = 1
function lightsequence() {
document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
}
<img id="light" src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png">
<button onclick="lightsequence()">Change Lights</button>
Change Lights
function lightsequence(){
document.getElementById("light").src
if(document.getElementById("light").src=="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png"){
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png"
}else if(document.getElementById("light").src=="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png"){
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Green.png"
}else{
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png"
}
}
<img id="light" src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png">
<button onclick="lightsequence()">Change Lights</button>
Related
Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>
I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one
I’m really new to JavaScript and trying to figure out a basic slide with pictures built in an array. Like you click next and previous to get new images.
How can I do that? Here is what I have so far.
<html>
<body>
<script>
imgArray = new Array(
“image”,
“image”
“image”);
x=1
y=2;
function move{
y = y+xflip;
if (y>x)
{y = 1;}
if (y==0)
{y = x;
document.images[2].src = img[y-1];}
</script>
<input type=“button” value=“Prev” name=“buttonp” onclick=“slide(-1)”>
<input type=“button” value=“Next” name=buttonb” onclock=“slide(1)”>
<img src=“image1”>
</body>
</html>
Please help. Thanks.
I like the jquery approach.
You could try something like this. You would need to add a bit extra logic for clicking previous at first go etc.
<button id=“buttonprev” type="button">Previous</button>
<button id=buttonforward”>Next</button>
<img id="preview" src="#" alt="your image" />
<script>
var imgArray = ['image1.png', 'image2.png', 'image3.png'];
var imgCount = 0;
$("#buttonforward").on('click', function(event) {
imgCount += 1;
$('#preview').attr('src', imgArray[imgCount]);
});
$("#buttonprev").on('click', function(event) {
imgCount -= 1;
$('#preview').attr('src', imgArray[imgCount]);
});
</script>
when I run this code it initially cant find the source "src="colour[var x]" " but once I have used colourChange it works fine, I just need to fix this one issue. any help would be much appreciated.
much thanks
src=[var x]
Javascript variables are not available in html elements attributes src="colour[var x]". So you have to initialize src with valid path value, or you can initialize it in js
...
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function colourChange(){
...
Like this
<!DOCTYPE html>
<html>
<head>
<title>Traffic Lights</title>
</head>
<body>
<img id="light" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW" width="150px" height="150px">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
<script>
var x=0;
var colour = ["https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ7t30uQ_C4eV-HXMFZU2EPlqQ_MwsMA2kEfkzBFjC3Sav4OM3n", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSNxgGXA3G2NwGVo70gZmy3ccYEcOSo4vzcPsgQRLbU_hGIBCWrnA", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSqFHvDm74NYMdbBtW-ZO9o3irXu4GHynOkDiCxDXJ484m1Ahyt"];
function colourChange(){
x += 1;
document.getElementById("light").src = colour[x];
if (x == 3) x = 0;
}
</script>
</body>
</html>
I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo
What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.
This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1
This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this 'div-'+(counter+1)
Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+Number(counter+1));
alert(nextDiv); // why does it return null
alert('div-'+Number(counter+1)); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle
Here is your answer:
<html>
<head>
<script>
function load()
{
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+(counter+1));
//alert(nextDiv); // why does it return null
//alert('div-'+(counter+1)); // while this doesn't?
nextDiv.style.display = "block";
counter++;
},true);
}
</script>
</head>
<body onload="load()">
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
</body>
<html>
To solve this kind of returning "null" values by getElementById("").
you can use script inside the body instead of head it will return the html element.
const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo">sample text</p>
<script src="script.js"></script>
</body>
</html>