Turning lights on and off - javascript

I am trying to make a program where when you click on a light the lightbulb will turn on, and then if you click on it again it will turn off. I have onClick but no matter which one I clikc the first one always turns on. Can somebody help so that the clicked on light will turn on?
<!DOCTYPE html>
<html>
<body>
<img id="light1" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<img id="light2" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<img id="light3" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<img id="light4" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<script>
function changeImage() {
var image1 = document.getElementById('light1');
if (image1.src.match("bulbon")) {
image1.src = "pic_bulboff.gif";
} else {
image1.src = "pic_bulbon.gif";
}
}
</script>
</body>
</html>

In JavaScript, event handlers get a special variable called this, which refers to the element from which the event was fired (in this case the light bulb that was clicked), you can use it like this:
function changeImage() {
if (this.src.match("bulbon")) {
this.src = "pic_bulboff.gif";
} else {
this.src = "pic_bulbon.gif";
}
}
Notice the difference from your code. You were always making changes to the first lightbulb, accessed by id using the API document.getElementById('light1').

You're pointing at the same DOM node in your function despite registering an event handler on multiple nodes.
You should use the this keyword to use currently clicked node as the context during the function's execution.

Related

HTML - Img alt attribute hides image

I'm grabbing favicon's from sites programmatically by generically making a request for the icon to "example.com/favicon.ico".
If the site doesn't have a favicon, I want to use the "alt" attribute of the image to hide the image so that it doesn't appear and doesn't have a "missing image" icon.
For example
<img src="https://www.businessinsider.com/favicon.ico" alt="$(this).hide();" height="16" width="16">
Can this be done?
You can use the built-in error() method. Hide your image based upon that.
$("img").on("error", function() {
$(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.businessinsider.com/favicon.ico" height="16" width="16">
If you want an alternative image when the image is not available, give the new image source.
$("img").on("error", function() {
$(this).attr("src", "https://homepages.cae.wisc.edu/~ece533/images/mountain.png");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.businessinsider.com/favicon.ico" height="16" width="16">
You can put your placeholder immediately and check if the image loads on script. If it loads, replace the img src
var thisImage = new Image();
thisImage.src = 'https://www.businessinsider.com/favicon.ico';
thisImage.onload = function() {
console.log("Image 1 ready to append");
document.querySelector('.bg-image').src = thisImage.src;
};
<!--The source here is your placeholder-->
<img class="bg-image" src="https://placekitten.com/50/50" height="50" width="50" />

On mouse hover, change picture in JavaScript

I have an image in my HTML code, and I want to make it so that when my mouse is hovering over the image, it will change to the other image, and when the mouse is not hovering over the image, it switches back to the default. How do I program this in a <script> tag?
No <script> tag necessary. Use onmouseover and onmouseout to change the image source.
onmouseover will execute an action when your mouse goes over the image. In this case, we use this.src to set the image src to another image.
onmouseout will execute an action when your mouse goes out of the image. In this case, we use this.src again to set the image to the default image.
<img title="Hello" src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681" onmouseover="this.src='https://www.ctvnews.ca/polopoly_fs/1.4037876!/httpImage/image.jpg_gen/derivatives/landscape_1020/image.jpg'" onmouseout="this.src='https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681'" />
You can use css for this like:
.react {
background: url('../img/React_Monoo.png');
}
.react:hover {
background: url('../img/React_Colored.png');
}
here react is a class name
var image = document.getElementById("image");
//Now, we need to add an Event Listener to listen when the image gets mouse over.
image.addEventListener('mouseover', function(){
image.src = "path/to/newimage"
})
image.addEventListener('mouseout', function(){
image.src = "path/to/otherimage"
})
You can use the on mouse out for this.
here is my Work on it.
<html>
<head>
</head>
<body>
<script>
function setnewimage() {
document.getElementById("img2").src = "myquiz1.png";
}
function setnewimage1() {
document.getElementById("img2").src = "myquiz2.png";
}
function setnewimage2() {
document.getElementById("img2").src = "myquiz3.png";
}
function setnewimage3() {
document.getElementById("img2").src = "pic33.png";
}
function setoldimage() {
document.getElementById("img2").src = "myquiz1.png";
}
</script>
<div>
<img id="img2" src="" width="300">
<br>
<img id="img1" src="myquiz1.PNG" onmouseover="setnewimage()"
width="300" onmouseout="setoldimage()">
<img id="img66" src="myquiz2.PNG" onmouseover="setnewimage1()"
width="300" height="200" onmouseout="setoldimage()">
<img id="img87" src="myquiz3.PNG" onmouseover="setnewimage2()"
width="300" height="200" onmouseout="setoldimage()">
<img id="img80" src="pic33.PNG" onmouseover="setnewimage3()"
width="300" height="200" onmouseout="setoldimage()">
</div>
</body>
</html>

How to stop javascript hover from activating all the other hovers?

I have a couple pictures I want to hover when you do mouseenter but once you hover over one image, all the other images change to mouseenter as well. How do I stop this from happening so you can hover one at a time without affecting the others?
<p><IMG SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f505b8a79bc462950c46/1469117701248/k_1.png/" ID="img1" onMouseEnter="doMouseenter()" onMouseLeave = "doMouseleave()"/></P>
<p><IMG SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f584be65943e371ac3c8/1469117828984/k_2.png/" align="right" ID="img2" onMouseEnter="doMouseenter()" onMouseLeave = "doMouseleave()"/></P>
<script language="Javascript">
function doMouseenter() {
document.getElementById("img3").src = "http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f6efd482e96f971b2dae/1469118191453/k_3_hover.png";
document.getElementById("img4").src = "http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f7cc8419c25e40f16e6b/1469118412438/k_4_hover.png";
}
function doMouseleave() {
document.getElementById('img3').src = "http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f603d482e96f971b24b2/1469117955279/k_3.png/";
document.getElementById('img4').src = "http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f759b8a79bc462952502/1469118297585/k_4.png/";
}
If you want, you can do like this:
<p><IMG SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f505b8a79bc462950c46/1469117701248/k_1.png/" ID="img1" onMouseEnter="this.src='http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f6efd482e96f971b2dae/1469118191453/k_3_hover.png'" onMouseLeave = "this.src='http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f603d482e96f971b24b2/1469117955279/k_3.png/'"/></p>
<p><IMG SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f584be65943e371ac3c8/1469117828984/k_2.png/" align="right" ID="img2" onMouseEnter="this.src='http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f7cc8419c25e40f16e6b/1469118412438/k_4_hover.png'" onMouseLeave = "this.src='http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f759b8a79bc462952502/1469118297585/k_4.png/'"/></p>
You're telling javascript to open both img3 and img4 when ever doMouseenter() is called.
This will modify the individual elements.
HTML
<p><img SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f505b8a79bc462950c46/1469117701248/k_1.png/" ID="img1" onmouseover="doMouseenter(this)" onmouseout="doMouseleave(this)"></P>
<p><img SRC="http://static1.squarespace.com/static/5736026127d4bd28d97e2b7a/t/5790f584be65943e371ac3c8/1469117828984/k_2.png/" align="right" ID="img2" onmouseover="doMouseenter(this)" onmouseout="doMouseleave(this)"></P>
JavaScript
function doMouseenter(obj) {
obj.style.opacity = 1;
}
function doMouseleave(obj) {
obj.style.opacity = 0;
}

Multiple image rollover in javascript with for loop

Please help me. I want to do the below activity in javascript programming with the help of "for loop".
Suppose there are five images on the web page. When I rollover the 1st image, the text should display "it's a first image". When I rollover the 2nd image, the text should display "it's a second image". When I rollover the 3rd image, the text should display it's a third image.
I have tried and it's successful but it's manual. I am new in Javascript programming..
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<link rel="stylesheet" href="style_latest.css" type="text/css">
<title>MATHERAN TRIP</title>
<style>
#displayText
{
width:413px;
height:auto;
background-color:#666666;
color:white;
}
#displayText1
{
padding-left:5px;
}
</style>
</head>
<body>
<img src="images/img1.jpg" id="img1" onmouseover="clickEvent1()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img2.jpg" id="img2" onmouseover="clickEvent2()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img3.jpg" id="img3" onmouseover="clickEvent3()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img4.jpg" id="img4" onmouseover="clickEvent4()" onmouseout="imgRollout()" width="100" height="100"><br/>
<div id="displayText">
<span id="displayText1"></span>
</div>
<script>
var myData=new Array("Hi, How r u?", "Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up?", "Hello, whats going on?", "Hi friends")
document.getElementById("displayText").style.visibility='hidden';
function clickEvent1()
{
document.getElementById("displayText1").innerHTML=myData[0];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent2()
{
document.getElementById("displayText1").innerHTML=myData[1];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent3()
{
document.getElementById("displayText1").innerHTML=myData[2];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent4()
{
document.getElementById("displayText1").innerHTML=myData[3];
document.getElementById("displayText").style.visibility='visible';
}
function imgRollout()
{
document.getElementById("displayText").style.visibility='hidden';
}
</script>
</body>
</html>
I would recommend you don't include inline event attributes at each element. But I would consider including an inline html5 data- attribute with the message associated with the elements:
<img src="images/img1.jpg" data-msg="Hi, How r u?" width="100" height="100">
<!-- etc -->
Then you can bind the same rollover functions to each element using a loop as follows:
function doMouseOver(e) {
document.getElementById("displayText1").innerHTML =
e.target.getAttribute("data-msg");
document.getElementById("displayText").style.visibility='visible';
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
var imgs = document.getElementsByTagName("img"),
i;
for (i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("mouseover", doMouseOver);
imgs[i].addEventListener("mouseout", doMouseOut);
}
Within the doMouseOver() function, the e argument is the event object, and thus e.target gives you a reference to the element the event happened to - so then you can retrieve the particular data-msg value for that element to display it.
Demo: http://jsfiddle.net/3c7Rb/
Having said that, you don't need the loop either. You can bind the functions directly to the document, and then within the mouse over handler you simply test whether the target element has the msg-data attribute. If it does, display it, otherwise do nothing:
function doMouseOver(e) {
var msg = e.target.getAttribute("data-msg");
if (msg) {
document.getElementById("displayText1").innerHTML= msg;
document.getElementById("displayText").style.visibility='visible';
}
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
document.addEventListener("mouseover", doMouseOver);
document.addEventListener("mouseout", doMouseOut);
Demo: http://jsfiddle.net/3c7Rb/1/

HTML JavaScript, how would I be able to make this function work using JavaScript by giving each element a different Id

am in need of some help with this simple function so it would be great if you could help me
so this is the function
<script>
function changeImage() {
element = document.getElementById('myimage')
if (element.src.match("bulbon")) {
element.src = "pic_bulboff.gif";
} else {
element.src = "pic_bulbon.gif";
}
}
</script>
<img id="myimage" onclick="changeImage()"
src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
so if you click the image then it would turn on, if you click again it would turn off, like a switch.
what if i have 5 images that are the same with different Ids and if say the 1st one is on then the last one would turn off, if the 3rd one is on then the 2nd one would turn off and so on, how would i create that function with multiple Ids and also give it this if statement, i just need an idea of how this can be written.
thank you for reading, it would be great to see your replies
Try this
<script>
function changeImage(element) {
if (element.src.match("bulbon")) {
element.src="pic_bulboff.gif";
} else {
element.src="pic_bulbon.gif";
}
}
</script>
<img id="myimage" onclick="changeImage(this)"
src="pic_bulboff.gif" width="100" height="180">
<img id="myimage1" onclick="changeImage(this)"
src="pic_bulboff.gif" width="100" height="180">
<img id="myimage2" onclick="changeImage(this)"
src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
Edit:
As suggested, this answer is insufficient for the question. If the OP wanted to toggle multiple bulbs the following could be done:
<script>
function changeImage(element, on) {
if (typeof element === 'string') {
element = document.getElementById(element);
}
if (on === false || bulbOn(element)) {
element.src='pic_bulboff.gif';
} else {
element.src='pic_bulbon.gif';
}
}
function bulbOn(element) {
return element.src.indexOf('bulbon') > -1;
}
</script>
<img id="myimage" onclick="changeImage(this); changeImage('myimage2', !bulbOn(this))"
src="pic_bulboff.gif" width="100" height="180">
<img id="myimage1" onclick="changeImage(this)"
src="pic_bulboff.gif" width="100" height="180">
<img id="myimage2" onclick="changeImage(this)"
src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
In this example, clicking the first image will always set the third image to the opposite state.
Modify your function to take an id as a parameter:
function changeImage(id) {
var element=document.getElementById(id);
if (element.src.match("bulbon")) {
element.src="pic_bulboff.gif";
}
else {
element.src="pic_bulbon.gif";
}
}
After that, it will be easy to connect them to the switches and make a custom behaviour relations.
For example, to make the 5th one toggle when you click the first one, just change the onclick for the first one into something like: onclick="changeImage('id_of_the_5th_image')"
For a more complex logic, you might want to have a function that will keep track of all the lights and turn on/off some of them appropriately. For example, when you click any bulb, it will check whether the first one is lit, and if so, it will turn off the fifth one, etc.
UPDATE
Here is a simple example, it uses the most complex scenario I mentioned in the comments: http://jsfiddle.net/ChDES/
could this jsfiddle be of any help?
HTML:
<div id="bulb1" class="bulb on"></div>
<div id="bulb2" class="bulb off"></div>
<div id="bulb3" class="bulb on"></div>
<div id="bulb4" class="bulb off"></div>
<div id="bulb5" class="bulb on"></div>
CSS:
.bulb {
width: 50px;
height: 25px;
background-color: #777;
}
.on {
background-color: #ff0;
}
JS:
jQuery(document).ready(function($) {
$('.bulb').click(function(e) {
$(this).toggleClass('on');
if (this.id == 'bulb1') {
$('#bulb5').toggleClass('on');
} else if (this.id == 'bulb2') {
$('#bulb3').toggleClass('on');
} else if (this.id == 'bulb3') {
$('#bulb4').toggleClass('on');
} else if (this.id == 'bulb4') {
$('#bulb1').toggleClass('on');
} else if (this.id == 'bulb5') {
$('#bulb2').toggleClass('on');
}
});
});
http://jsfiddle.net/laruiss/SZz5Y/1/
Anyway, it makes a funny game ;-) (Try to turn all the lights on or all the lights off).

Categories