How can I turn the bul on and off: but with only using 1 button? - javascript

It´s a code from w3schools.
I want to turn the bul on and off but with the same button.
As simple as possible.
Thx for every answer :)
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
</body>
</html>

Here's one way to do it.
// Add an on-click handler to the button
document.getElementById("action-btn").onclick = (e) => {
// Get the image
let image = document.getElementById("myImage");
// Check for the word "off"
if (image.src.includes("off")) {
// Set image to alternate
image.src = "pic_bulbon.gif";
// Set text of button
e.srcElement.textContent = "Turn off the light";
}
else {
image.src = "pic_bulboff.gif";
e.srcElement.textContent = "Turn on the light";
}
}
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<button id="action-btn">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">

Related

Javascript button slideshow

I am new to the javascript programming so can someone help me.
This is my code
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.innerHTML="src=/'https://picturejs.org/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
Change your colorIt function to the following. You need to set the src and then set the display to block. You might also want to move the height and width to CSS.
function colorIt(e) {
pic.src='https://picturejs.org/adv/banner.jpg';
pic.width = 400;
pic.height = 150;
pic.style.display = "block";
}
function fillIt(e) {
pic.innerHTML="src=/'https://picturejs.org/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
}
The Source for the image in JavaScript is invalid. You used HTML hyperlinks in JS.
.innerHTML modifies the content between the opening and closing tags (<div>THIS</div>), not the content of the tag itself (<div THIS></div>).
You can modify the tags attribute using setAttribute or by setting a property directly:
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.src='https://picturejs.org/adv/banner.jpg'
pic.width='400px'
pic.height='150px'
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
You were on the right track. However, you need to set each property in JS.
ALso I could not get picturejs.org to load so I placed a picsum pic in there instead.
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.src='https://picsum.photos/150/400'
pic.width='400'
pic.height='150';
pic.style.display='block';
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
Please try the below code:
function fillIt(e) {
pic.style.display = "block";
pic.src ="https://libertycity.net/uploads/download/gta5_lamborghini/thumbs/4qhllsfhd8fk9bm4mf36761u37/15205818409903_63e23c-pgta535987529.jpg";
}
You need to add the root of your image in , for example depeding on where you have the image downloaded in your PC.
Hope this helps !

How to create a button that will change background color

I need help coding in HTML. I have tried many different ways of coding this button. The button is on the webpage now but will not change the background color of the web page.
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.getElementByld("background").sytlecolor="blue";
</script>
</body>
</html>
I would recommend you to go through Javascript DOM and HTML
function myFunction(){
document.getElementsByTagName("body")[0].style.background="blue";
}
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
</body>
</html>
Try this:
var isBlue = false;
document.querySelector("button").addEventListener("click", function(){
if(isPurple){
document.body.style.background= "white";
}
else{
document.body.style.background= "blue";
}
isBlue = !isBlue
})
This will not only change the background colour but will create a button that toggles it.
Try this
<body>
<button type="button" onclick="myFunction()">Click to change color</button>
<script>
function myFunction(){
document.body.style.background = "aqua";
}
</script>
</body>
</html>```
background is not a document object. It is an html dom object.
Add this line in HTML Body
<a onclick="changecolor('navy')" id="navy">#0E2A36</a>
You can add customize color in CSS like
#navy{
background:#0E2A36;
}
Then add JavaScript
<script type="text/javascript">
function changecolor(id) {
document.body.style.background = document.getElementById(id).innerHTML;
}
</script>
There are few spelling mistakes but this should explain
1.make the element a variable.
2. set that variable with .style.background = "blue"
spelling mistakes:
sytle = style
getElementByld = getElementById
<html>
<body>
<div id="background">
<button type="button" onclick="myFunction()">Blue</button>
</div>
<script>
function myFunction() {
//get the element
const background = document.getElementById("background");
// set it to blue
background.style.background = "blue";
}
</script>
</body>
</html>
hope this helps.
You have two errors here:
You are selecting an element by id, but that element doesn't exists on your html.
Your javascript have a sintax error. (Missing closing brackets on your function.
You are using the property sytlecolor that doesn't exists (there's a typo on style, and even this way, stylecolor doesn't exists. Use style.backgroundColor instead.
Here's a working example:
<html>
<body id="background">
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.getElementByld("background").style.backgroundColor = "blue";
}
</script>
</body>
</html>
Also if you want to change the body background color, you don't need to put an id on it:
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.body.style.backgroundColor = "blue";
}
</script>
</body>
</html>
I'll go with
//On top goes the head
<button type="button">Blue</button>
And then I would create a JS file
var button=document.querySelector('button'),
body =document.querySelector('body');
button.addEventListener('click',function(){
body.style.backgroundColor="blue";
});
That should turn the background blue.
Add id of the specific element whose background you want to change
document.getElementsByTagName('body')[0].style.background='green'
<html>
<body>
<button type="button"
onclick="document.getElementsByTagName('body')[0].style.background='green'">
Click for green backgournd
</button>
<br />
<br /><br />
Another way to do from text box Just for your reference
<br />
<input style="width:100%" type="text" id="txtColorBox" placeholder="enter color name and click button"/>
<br/>
<button type="button"
onclick="document.getElementsByTagName('body')[0].style.background=document.getElementById('txtColorBox').value">
Click for green backgournd
</button>
</body>
</html>
Try this in your function
function myFunction(){
document.body.style.background = "blue";
}
There are two methods to this with vanilla javascript and the second is jQuery.
In your case, you are not using jQuery. So the solution is vanilla javascript.
function myFunction(element) {
element.style.backgroundColor="green";
}
<button type="button" onclick="myFunction()"> Blue</button> //Change web bg
if you need to change the button background. Pass the current pointer.
<button type="button" onclick="myFunction(this)"> Blue</button> //Change buttion bg
bg => background
Hi you could do something like so:
document.getElementById('buttonColor').addEventListener('click', () =>
document.body.style.backgroundColor = "blue"
);
<html>
<body>
<button id="buttonColor">Change Color</button>
</body>
</html>

How to make a button that will only appear after 5 seconds using Javascript?

The title pretty much says it all: I need help in making a button that will only appear 5 seconds after the page loads.
this is the code i'm working with:
<html>
<body onload="setTimeout(showStuff, 5000)">
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class=login align=center>
<font size=13 face=helvetica> You're doing that too much. </font><br> <br> <br>
<font size=5 face=helvetica>
You have entered the wrong username/password too many times <br>
<br><br>
<br><br>
Click "OK" to go back to the log-in page <br> <br>
<p id="Button"><input type=submit onclick="myFunction()" id="Button" value="OK"> </p>
<script>
document.getElementById("Button").style.visibility = "hidden";
function showStuff(Button){
document.getElementById("Button").style.display = "inline";}
function myFunction() {
window.location = "project.html"}
</script>
</div> </font>
</body>
</html>
This is probably what you need
<body>
<button id="some-button">button</button>
<script>
document.getElementById("some-button").style.display = "none";
function showStuff() {
document.getElementById("some-button").style.display = "inline";
}
function myFunction() {
window.location = "project.html"
}
setTimeout(showStuff, 5000);
</script>
</body>
</html>
Things you should know
* The html element <font> is deprecated
* Is bad practice to mix Javascript code inline with html.
* Do not duplicate html elements ids, they should be unique (Thanks Calvin Nunes)
How to fix your code
* Close the second <font> element correctly and delete the unnecesary id of the button.
* If you use display = 'inline', then to hide the element use display = 'none'
The working code
<html>
<body onload="setTimeout(showStuff, 5000)">
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class=login align=center>
<font size=13 face=helvetica> You're doing that too much. </font><br> <br> <br>
<font size=5 face=helvetica>
You have entered the wrong username/password too many times <br>
<br><br>
<br><br>
Click "OK" to go back to the log-in page <br> <br>
</font>
<p id="Button">
<input type=submit onclick="myFunction()" value="OK"> </p>
<script>
document.getElementById("Button").style.display= "none";
function showStuff(){
document.getElementById("Button").style.display = "inline";
}
function myFunction() {
window.location = "project.html"
}
</script>
</body>
</html>
<script>
function showStuff(){ // no argument needed
document.getElementById("Button").style.display = "inline";
}
</script>
<body onload="javascript:setTimeout(function(){ showStuff(); }, 5000)">
function definition should be before function call
in function showstuff no argument is needed. a use function() inside settimeout to execute correctly . if not it will just execute without delay .
Well using jquery you can have the button within the div, something like
<div id="div_id">Button here</div> and set time out to display it
setTimeout(function(){
$('#div_id').show();// or fade, css display however you'd like.
}, 5000);`
or with Javascript:
function showItbutton() {
document.getElementById("div_id").style.visibility = "visible";
}
setTimeout("showItbutton()", 5000); // after 5 secs
First, use DOMContentLoaded event and then write the code within that handler to handle this logic:
<script>
window.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
// Assuming button has id 'myButton'.
document.querySelector('#myButton').style.display = 'none';
}, 5000);
});
</script>
Remember DOMContentLoaded is the key to detect page load. You can use onload depending on your situation. Refer this to understand the difference between the two.
setTimeout() receives milliseconds, not seconds.
So 5000 it will work for you.
JS:
setTimeout(showStuff, 5000);
console.debug('Start page');
function showStuff(Button){
console.debug('Display');
document.getElementById("Button").style.display = "inline";
}
HTML:
<button id="Button" style="display:none">Button</button>

Trying to Target a button

hi I'm trying to target a button to a div using iframe .. I tried so much but no result...
<html>
<body>
<div id="one">
<button type="submit" onclick="ShowResult()" formtarget="result"> Calculate </button>
</div>
<div id="two">
<iframe name="result"></iframe>
</div>
</body>
javascript:
function ShowResult()
{
document.write("someword");
}
it seems true but when I click the button it open a blank page showing what in the function.. help ??
You are missing alot,
First do not practice "onclick()" anymore.
Second do not practice "document.write" anymore.
I have rewrite your code, enjoy..
HTML
<div id="one">
<button type="submit" id="functionThis" formtarget="result"> Calculate </button>
</div>
<div id="two">
<iframe id="iframe1" name="result"></iframe>
</div>
JS
document.getElementById("functionThis").addEventListener("click", showResult, false);
function showResult() {
var htmlString = "<body>Some Words</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src = "javascript:'" + htmlString + "'";
}
Fiddle
working fiddle

How to switch 4 images using a button

<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.
Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.
Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>
What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>

Categories

Resources