<!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.
Related
I created a button that uses function fontColor to activate the id= "main header". I'm trying to get the parameters of function to accept arguments to adjust the font size and color in the id="Main Header". Can I get some help with this? Thanks.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="script.js"></script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button type="button" onClick="fontColor(30,"blue");" id="push">Change.</button>
<h1 id="Main Header"> HI</h1>
<p id="this one">Hello World</p>
</body>
</html>
function fontColor(s, c) {
var size = element.style.fontsize(s);
var color = element.style.color(c);
var result = [size, color];
document.getElementById("Main Header").innerHTML = result;
}
Just set the id to a variable, and change it from there. Also, as the other user said, fontSize should be suffixed with px
function fontColor(s, c) {
var changing = document.getElementById("Main Header");
changing.style.fontSize = s;
changing.style.color = c;
}
Camel-case element.style.fontSize
I could be wrong but also I believe element.style.fontSize needs a string so fontColor("30px","blue")
EDIT: element is undefined and there's more errors than I previously thought. I couldn't just tell you how to fix the errors so I just rewrote your function.
A better solution would be:
function fontColor(s, c) {
var element = document.getElementById("MainHeader"); <- should be one word
element.style.fontSize = s;
element.style.color = c;
}
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>
I'm writing some simple code to change the visibility of an image when a button is clicked, but my document.getElementById().value is coming up as undefined. (I've tried replacing .value with .display - same result).
What could be the problem?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script>
function hideImage(imageId){
document.getElementById(imageId).visibility="hidden";
}
function showImage(imageId){
document.getElementById(imageId).visibility="visible";
}
function switchVis(imageId){
var curVis = document.getElementById(imageId).value;
if(document.getElementById(imageId).value=="hidden"){
document.getElementById("output").innerHTML="hidden";
showImage(imageId);
}
else if(document.getElementById(imageId).value=="visible"){
hideImage(imageId);
document.getElementById("output").innerHTML="visible";
}
else{
alert("Visibility Issue!\nVisibility value is " + curVis);
}
}
</script>
</head>
<body>
<img src="images/k3.gif" id="k3"><p>
<button onclick=switchVis('k3')>Visibility</button>
<div id="output"></div>
</body>
You cannot simply get style value by using document.getElementById().value . getComputedStyle() gives the final used values of all the CSS properties of an element. The returned style is a CSSStyleDeclaration object which can be used to get the value of your style. Try follwing code. It should work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script>
function hideImage(imageId){
document.getElementById(imageId).style.visibility="hidden";
}
function showImage(imageId){
document.getElementById(imageId).style.visibility="visible";
}
function switchVis(imageId){
var curVis = document.getElementById(imageId); //your element
style = window.getComputedStyle(curVis); //returns CSSStyleDeclaration object
curVis = style.getPropertyValue('visibility'); //now get your css value
if(curVis=="hidden"){
document.getElementById("output").innerHTML="visible";
showImage(imageId);
}
else if(curVis=="visible"){
hideImage(imageId);
document.getElementById("output").innerHTML="hidden";
}
else{
alert("Visibility Issue!\nVisibility value is " + curVis);
}
}
</script>
</head>
<body>
<img src="images/k3.gif" id="k3" value="check"><p>
<button onclick="switchVis('k3')">Visibility</button>
<div id="output"></div>
</body>
You can get visibility like that: jsfiddle
So it's in document.getElementById('myId').style.visibility
//to make visible
document.getElementById('myId').style.visibility='visible'
//to make hidden
document.getElementById('myId').style.visibility='hidden'
Instead of value you used there's innerHTML. Value is for input elements.
try this
to show
document.getElementById('k3').style.visibility='visible';
to hide
document.getElementById('k3').style.display='none';
refer this for better idea
Add visibility property in img tag.
visibility="visible"
2.Also check visibility value with following.
document.getElementById(imageId).style.visibility=="visible"
Use same thing in hideImage and showImage function.
I am trying to use Javascript to swap an image, so far I can get it from A to B, but not back.
Here is what I'm using to create one swap:
<img src="pic1.png" name="pic" onclick="window.document.pic.src='pic2.png';"/>
This swaps image 1 to image 2, simple enough. But I want to be able to revert back to image 1 by clicking on the new image 2. I tried using this:
<img src="pic1.png" name="pic" onclick="
if (window.document.pic.src='pic1.png'){
window.document.pic.src='pic2.png';
}
else if (window.document.pic.src='pic2.png'){
window.document.pic.src='pic1.png';
}"/>
It doesn't seem to work in this instance. It will switch to pic2, but not switch back to pic1. Is it something to do with onclick? My if statements? Thanks
Try this simple trick... easy to maintain.
<script>
var onImg= "on.jpg";
var offImg= "off.jpg";
</script>
<img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>
In your code the problem is
when you alert window.document.pic.src its print like http://localhost/pic1.png
and then you are are use condition if (window.document.pic.src == 'pic1.png')
how is it true.
try this
<script type="text/javascript">
function test()
{
alert(window.document.pic.src);
//alert msg print like http://localhost/test/pic1.png
if (document.pic.src=='http://localhost/test/pic1.png'){
document.pic.src='pic2.png';
}
else if (document.pic.src=='http://localhost/test/pic2.png'){
document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>
wrong use of == in if condition
if (window.document.pic.src == 'pic1.png'){
window.document.pic.src='pic2.png';
}
else if (window.document.pic.src =='pic2.png'){
window.document.pic.src='pic1.png';
}"/>
window.document.pic.src='pic1.png' assigns pic1.png to the left hand side. It does NOT compare.
Though not directly relevant, try not to access elements by their name globally. Use their id.
Your javascript should not be inside the onclick. It should be inside a javasctipt function
Combined:
The img tag:
<img src="pic1.png" name="pic" id="pic" onclick="swap()"/>
The javascript
<script>
function swap()
{
if (document.getElementById("pic").src.endsWith('pic1.png') != -1) //==:Comparison
{
document.getElementById("pic").src = "pic2.png"; //=:assignment
}
else if (window.document.pic.src.endsWith('pic2.png') != -1)
{
document.getElementById("pic").src = "pic1.png";
}
}
</script>
Your code is doing what the below lines do, it's not going inside an if else block, so if you remove your if else block the code still will work, because on mouse click it sets the value of src as 'pic2.png', which was 'pic1.png' earlier, and when you click again because it's already pic2.png so it remains the same.
<html>
<head>
<script type="text/javascript">
function swap() {
window.document.pic.src='pic2.png';
}
</script>
</head>
<body>
<img src="pic1.png" name="pic" onclick="swap()">
</body>
</html>
You can try this.
<html>
<head>
<title>Swapping Images</title>
</head>
<body>
<img id="myimg" src="img1.jpg" hieght="300" width="300" onClick="change ()"/>
</body>
</html>
<html>
<head>
<script>
function change () {
var img=document.getElementById("myimg");
if (img.src === "img1")
img.src="img2.jpg";
else
img.src="img1.jpg";
}
</script>
</head>
</html>
I am following a JavaScript tutorial on the W3Schools website and I have the following code:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<script type="text/javascript">
function confirmShow
{
var r = confirm("Press one...")
if (r == true)
{
alert("Button pressed == OK")
}
if (r == false)
{
alert("Button pressed == Cancel")
}
}
</script>
<input type="button" onclick="confirmShow()" value="Show Confirm Box" />
</body>
</html>
and whenever I preview it in Coda or in Safari the alert never shows up.
Thanks in advance!
"function confirmShow" => "function confirmShow()"
Firebug is good for js debugging, try it. Safari has options too, AFAIK.
function confirmShow
{
function confirmShow()
{
?
I don't know if this is your problem, but your button is outside the <body> tag. That might cause you some trouble...
Also one would usually put a script like this in the <head> element. Just FYI.
1) w3schools is filled with errors and omissions. Better tutorials can be found at howtocreate.co.uk
2) You have no DOCTYPE declaration, and you're using XHTML syntax.
2.1) IE doesn't support true, see webdevout.net/articles/beware-of-xhtml for more information
3) You need to encapsulate the within a element as well as another block-level element as per the specification
See below for a proper HTML5 document. Notice the location and syntax
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script>
function confirmBox() {
var ret = confirm('Some Text');
/*
Note the 3 equal signs. This is a strict comparison operator, to check both the 'value' as well as the type. see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators for more
*/
if(ret === true) {
alert('Alert box for "Okay" value');
}
else if(ret === false) {
alert('Alert box for "Cancel" value');
}
}
window.onload = function() {
// Execute the confirmBox function once the 'button' is pressed.
document.getElementById('confirmBox').onclick = confirmBox;
}
</script>
</head>
<body>
<form>
<p>
<input type="button" id='confirmBox' value="Show Confirm Box">
</p>
</form>
</body>
</html>