I'm trying to create a simple toggle button with JavaScript and the else part is not working. The lamp is just turning on and then it stops working. How do I solve this?
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='../Media/lighton.gif'>
<script>
function toggleBulb() {
var doc = document.getElementById('light')
if (doc.src == '../Media/lightoff.gif') {
doc.src = '../Media/lighton.gif'
} else if (doc.src == '../Media/lighton.gif') {
doc.src = '../Media/lightoff.gif'
}
}
</script>
</body>
</html>
This is the difference between a property and an attribute. The attribute is the text in the HTML that you can see in the markup, but this is not always the same as the property by the same name. In this case, the property src is the evaluated URL represented by the src attribute. You'll notice that in my demo, I have a src attribute that begins with //, which tells the browser to use the current page's protocol for this resource, matching the page. The calculated property has https:// for the protocol because this stackoverflow page has an SSL installed. In the end, you should use .getAttribute() when comparing attributes.
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='//placehold.it/100/FF0/000?text=ON'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
if (doc.getAttribute('src') == '//placehold.it/100/000/FFF?text=OFF') {
doc.src = '//placehold.it/100/FF0/000?text=ON'
} else if (doc.getAttribute('src') == '//placehold.it/100/FF0/000?text=ON') {
doc.src = '//placehold.it/100/000/FFF?text=OFF'
}
}
</script>
</body>
</html>
As I mentioned in a comment the src is the full path on this file based on the website it's on. Instead one other you could do is check if the src ends with the string you are looking for:
function toggleBulb() {
var doc = document.getElementById('light')
if (doc.src.endsWith('/Media/lightoff.gif')) {
doc.src = '../Media/lighton.gif'
} else if (doc.src.endsWith('/Media/lighton.gif')) {
doc.src = '../Media/lightoff.gif'
}
}
Or you could check/set the full paths instead. Also not the else if can be made into just an else, unless you are planning to add more to that logic.
As others have said, your are checking the src property for an exact match, but that property will always return the full URL, and you aren't testing against full URLs, so you'll never get a match.
However, unlike the other answers, it's best to use .indexOf() to check the image source string to see if it contains a sub-string. Then it won't matter which value you get for the source (src attribute or full path). .indexOf() returns the index position of the substring or -1 if it can't be found.
Also, the if/then can be simplified using JavaScript's ternary operator:
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='//placehold.it/100/FF0/000?text=ON'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
// If the source contains "lightoff", set it to "lighton", otherwise set it to "lightoff"
doc.src = doc.src.indexOf('../Media/lightoff.gif') > -1 ? "../Media/lighton.gif" : doc.src;
}
</script>
</body>
</html>
You have to write full code at each and every place where you are comparing the images. Also doc.src returns A String, representing the URL of the image, including the protocol like- (http:///now here the full path of image.
if you code are running on localhost then file:///now here the full path of image.) I have added this in the code and it'll run correctly.
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding: 20px;" id='light' src='**insert your full path of image here**'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
if (doc.src== "file:///insert your full path of image here")
{
doc.src='insert your full path of image here';
}
else if (doc.src == "file:///insert your full path of image here") {
doc.src='full path of image here';
}
}
</script>
</body>
</html>
Related
<!DOCTYPE html>
<html>
<head>
<title>switch</title>
<script language="javascript" type="text/javascript">
function click_turn() {
if (document.getElementById("light").src == "/pic_bulboff.gif") {
document.getElementById("light").src = "/pic_bulbon.gif";
}
else {
document.getElementById("light").src = "/pic_bulboff.gif";
}
}
</script>
</head>
<body>
<img id="light" src="/pic_bulboff.gif" />
<br />
<button id="click" onclick="click_turn()">Click</button>
</body>
</html>
The button doesn't work, that is the light bulbs doesn't turn on. I searched in Google and didn't find any solution. What did I do wrong?
The HTMLMediaElement.src property reflects the value of the HTML media element's src attribute, which indicates the URL of a media resource to use in the element.
Instead of using src property, you should be using getAttribute to read the attribute of the Element which would not be URL but a value assigned.
function click_turn() {
if (document.getElementById("light").getAttribute('src') == "pic_bulboff.gif") {
document.getElementById("light").setAttribute('src', "pic_bulbon.gif")
} else {
document.getElementById("light").setAttribute('src', "pic_bulboff.gif")
}
}
<base href="https://www.w3schools.com/js/">
<img id="light" src="pic_bulboff.gif" />
<br />
<button id="click" onclick="click_turn()">Click</button>
using img.src will return an absolute path not a relative path so the document.getElementById("light").src will never equal to /pic_bulboff.gif. You can also add the baseurl to your logic or use .includes("") instead:
function click_turn() {
if (document.getElementById("light").src.includes("pic_bulboff.gif") {
document.getElementById("light").src = "/pic_bulbon.gif";
}
else {
document.getElementById("light").src = "/pic_bulboff.gif";
}
}
document.getElementById("light").src returns the full path ('http://etc').
try document.getElementById("light").src.endsWith("/pic_bulboff.gif")
Well, I replaced "==" by "endsWith" and it worked. Thank you for all the help.
Could someone please explain why the following code below doesn't run an automated sequence of images'. I was able to do this before with my code prior to this now that I have edited it slightly the automation doesn't work.
<!DOCTYPE html>
<html>
<body>
<img id="Light" src="./red.jpg">
<button type="button" onclick="ChangeLights()">Change Lights</button>
<script>
var List = [
"./red.jpg",
"./redyellow.jpg",
"./green.jpg",
"./yellow.jpg",
];
window.onload = "ChangeLights()";
var index = -1;
function ChangeLights() {
index ++;
var image = document.getElementById('Light');
image.src = List[index % List.length];
}
setInterval(ChangeLights, 1000)
</script>
</body>
</html>
It works fine, but you can change Array to a different name and call ChangeLights(); without "" in line 18 .
The automation works, but the path to the images is wrong, you should fix that by pointing to the right folder, probably by removing the "./" on "./NAME_OF_THE_IMAGE".
This is the code I am currently working with: I need to display a starting image (preferably green) and then, every time the button is clicked, the image needs to change to trafficlight and then to the other image which it didn't start as. e.g it needs to go from green to orange then red then back to orange etc.
<!DOCTYPE html/>
<html>
<script type="text/javascript">
var trafficlight = [];
trafficlight [0] = " http://4vector.com/i/free-vector-traffic-light-green- clip-art_117820_Traffic_Light_Green_clip_art_medium.png ";
trafficlight [1] = "http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_ dan_01.svg.med.png ";
trafficlight [2] = "http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png ";
var num = 0;
function changepic()
{
if (num>=trafficlight.length-1){
num=0;
}
num=num+1;
document.trafficlight.src=trafficlight[num];
}
</script>
</head>
<body>
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p>click here</p>
</center>
</body>
</html>
As noted by Jonas W - you are trying to referecnce the image but using the wrong reference. You can either do it via an id or using the name as you have. Note that if you are using the name then you need to reference it with a [0] after it as I have in the post - this is because getting the element by name will return an array like object - so you need to specify that its the first item in that. Also your image src for the orange light is broken. The folowing works and allows swapping of the src (with the exception that the yellow light image does not display).
var trafficlight = ["http://4vector.com/i/free-vector-traffic-light-green-clip-art_117820_Traffic_Light_Green_clip_art_medium.png","http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_dan_01.svg.med.png","http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png"];
function changepic()
{
var imageSrc=document.getElementsByName('trafficlightpic')[0].src;
var num =trafficlight.indexOf(imageSrc);
if (num >= trafficlight.length-1){num=-1;}
num+=1;
document.getElementsByName('trafficlightpic')[0].src=trafficlight[num];
}
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p onclick="changepic();">click here</p>
</center>
document.trafficlight doesn't exist. You need:
document.getElementById("trafficlightpic").src=trafficlight[num];
instead. And you should change name="" to id="" in the img element. That should work.
I was trying to get a run-time value(msg.payload) from a function node(node-red) and supply it to a template node(node-red) to display appropriate image according to the input.I used the below code,but the image is not changing according to the choice of input. Below is the code. Please take a look and provide me some insights or what needs to be changed to make it work.
<html>
<head>
<script type="text/javascript">
function displayImage() {
var j=parseInt({{payload}});
document.getElementById("img").src = images[j];
}
function startTimer() {
setInterval(displayImage,3000);
}
var images = [];
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload="startTimer()">
<img id="img" src="image1.jpg"/>
</body>
</html>
Use the console.log(message)and check:
the {{payload}} parameter should be an integer as you expected
the value of J parameter, after its assignment, should an integer between 0-2
You are dealing with NodeRED. The easiest way to learn about your payload parameter is to use a Debug node (the dark green one) and attach it to the same output as the template node. You then will very quickly see what it is made of. Most likely your payload is a JSON object. Something like this:
{ "name" : "Peter",
"color" : "Blue",
"image" : "2"
}
... or similar.
Then you just change that content in {{ }} to reflect the variable inside the JSON object that has the number you are interested in. Like:
{{payload.image}}
Double check your function node. If it doesn't end with a return statement (typically return msg) you simply won't have any input.
I have a simple javascript code which sets a div's display = "block" then display="" (an empty value) but when I try to get value of display style using both Jquery and native javascript, both returns value as "block" after resetting it to a blank value.
How can I get the proper value(blank value) using any of these two?
I need to set it to blank instead of 'none', as it has been used in the product at thousands of places.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.0.js"></script>
<script type="text/javascript">
function getDivStyle(){
var myDiv = document.getElementById("testDiv");
var before = $('#testDiv').css('display');
$('#testDiv').css('display', '');
var after = $('#testDiv').css('display');
var computed = getComputedStyle(myDiv).getPropertyValue("display");
console.log("before-> " + before +" ---- after-> "+ after+" ---- computed-> " + computed);
};
</script>
</head>
<body>
<div id="testDiv" style="display:block; height:100px; width:500px; border: 1px solid red;">
test div
</div>
<input value="get style" type="button" onclick="getDivStyle()"></input>
</body>
</html>
Got it, as per all the comments above, the proper way to set turn off display is to set display = "none". But in this case, if it is set to a blank value to get the value we can use
element.style.display;
as this returns a blank value.
The Syntax for display is
display: value;
If you do not want your element to be displayed then you need to change it to none or any other value you want. If you set it to blank then it will take the default value.
Edit:
This seems to work
document.getElementById("testDiv").style.display