Significance of two different img's in the given code? - javascript

It is a link to w3schools Website for a JS tutorial
In the above program I found that there are two src's of image in the ( if loop ) i.e. img src="pic_bulboff.gif" and img src= "pic_bulbon.gif". Why is there a need for two img src's?
What is the use of "match" in this program?

The src attribute is the URL for the image - it's what gets displayed. That's not a loop, it's an if statement - a branching or conditional statement - and only one of the branches will be taken each time the function is called. It is a toggle - when you click the light, it switches the src attribute to the one not currently selected.
match is a function on a string that takes a regular expression. If you are just getting started programming, that's a deep rabbit hole to go down, but basically it's checking whether the current src attribute value contains that text or not.

It is checking if the image is the bulbon image, if it is then it changes it to the bulboff image and vice-versa.

To answer your question let's look at the whole code:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Can Change Images</h1>
<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>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
</body>
</html>
As the problem states, the whole point is to change<img> src attribute upon clicking the <img> tag.
That implies that if the light is on, meaning if the src attribute of the <img> tag contains the word off, we want to change the src to be src="pic_bulbon.gif". This should work like a normal light bulb, on and off. Each image represents a bulb that is off or a bulb that is on.
Match is the key to the solution. What match does is that it will look at a string and find a word within that string, if such word exists then it will return true.
Using match on the string from the src attribute will help us to find a the word on or off*. So considering what the src attribute contains, pic_bulbon**.gif or pic_bulboff.gif, we will match like so in JavaScript:
stringName.match(someOtherString), which translates to image.src.match("bulbon") or image.src.match("bulboff") conversely.
After this we can set the src attribute to on or off via the if/else statement:
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
If you still have any questions please ask in the comments below.

This is what the code is doing: Working Example with logging
function changeImage() {
// grab the element (in this case an img tag) using the id 'myImage'
var image = document.getElementById('myImage');
// check to see if the source of the image contains the word 'bulbon'
// match return an array of matches
if (image.src.match("bulbon")) {
// if there is a match for bulbon change the image src to pic_bulboff.gif
image.src = "pic_bulboff.gif";
} else {
// if not change it to pic_bulbon.gif
image.src = "pic_bulbon.gif";
}
}
// on match:
var s = 'aaaabulbonaaa';
var matchResult = s.match('bulbon');
// match return an array of matches
console.log(matchResult); // ["bulbon"]

Related

trying to grab image url within div's children

I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");

Show base64 image next to canvas with charts.js

I'm using charts.js which has an option to add an attribute containing a base64 image of the canvas, like this:
animation: {
onComplete: function(animation){
document.querySelector('#myChart').setAttribute('href', this.toBase64Image());
}
},
Here is the full working fiddle: https://jsfiddle.net/0on3f7t7/
When you inspect the canvas you can see a href attribute containing the image, so that works. But instead I need to display the image below the canvas. So, yes, there will be two charts on the screen, the canvas version and the image version.
I can't find an answer to this question anyway, and the documentation doesn't give any clues.
You need to add an <img> element to your page, and then set the src attribute of the <img> element to the output of this.toBase64Image()
See the following fiddle:
https://jsfiddle.net/wveepa7c/
onComplete: function(animation){
// #myImage is an img element
document.querySelector('#myImage').setAttribute('src', this.toBase64Image());
}
onComplete is called at least two times at jsfiddle. You can define a variable which is undefined, at onComplete check if variable is defined to prevent <img> being appended to document twice, if variable is not defined, create <img> element, use .insertAdjacentHTML() chained to ctx with first parameter "afterend" and second parameter .outerHTML of <img> element
var img;
animation: {
onComplete: function(animation) {
if (!img) {
ctx.setAttribute('href', this.toBase64Image());
img = new Image;
img.src = ctx.getAttribute('href');
ctx.insertAdjacentHTML("afterend", img.outerHTML)
}
}
}
https://jsfiddle.net/0on3f7t7/2/

Javascript - Can someone please explain this code

I am learning to code in JavaScript and my assignment was to find out what each line of this code means. I've tried to figure out some of the code but the part which confuses me most is the functions,'div classes',document.createElement('something') and the append.Child('something').I have researched on the internet but it is vaguely explained. Please can someone explain each line of the code;here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Traffic lights</title>
</head>
<script>
var images = ['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber Light.jpg'];
var index = 0;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
</script>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="setInterval(changeImage, 3000)">NextImage</button>
</body>
Thanks in advance
First Part:
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
This function
first create dynamic html tag of image
Assign Image src/path that contained in the var images =
['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber
Light.jpg'];
first get html tag that has id name content then append it means
to hold the previous and next images
Second Part:
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
This function
first initialize the img variable with the content/image that hold
in content div by access through an array index Increment to
access other image
using Modulus logic to get images that are on 4 index
Relace srcwith existing
This code displays an image when the page is loaded, then changes the image every 3 seconds after the user clicked the button once. Here is how it works:
buildImage is a function that creates an <img /> element (document.createElement) and set the source (img.src) attribute to one of the sources listed in the array images. Which one exactly depends on the index variable. It then adds the element to the html page, under the div with the id content (getElementById('content').appendChild(img)). So you end up with:
<div class="contents" id="content">
<img src="redlight.jpg" />
</div>
The function is called only once, when the page is loaded (see the onload attribute).
changeImage changes the image source (img.src). the code
document.getElementById('content').getElementsByTagName('img')[0]
means "get the div with id = content, then find all the html tags "img" and return the first one".
the code
index++; index = index % 4;
increments the index variable, but ensure it is never more than 4 (the size of your array, see the modulo operator).
Finally, the setInterval is a function which takes a function name and a duration in milliseconds. Once called, it will run the function every X ms.
!!
In this code, the setInterval function is called on every click. It might be problematic. I would change it if I were you.
document.createElement('img') creates a new <img /> tag. img.src = images[index] takes the path of the first element inside images (because index is set to 0 at the beginning) and sets the source (='redlight.jpg'). With document.getElementById('content').appendChild(img) you add the created <img src='redlight.jpg' /> tag inside your <div> with id = 'content'.
div class='contents' defines that your div is using the css class 'contents'. This css class handles the styling of your div element.
There are really good explanation for this all at http://www.w3schools.com/. You should study that page.
For the parts that you are insecure about.
Function
Functions is a big subject itself. It's a huge part of about every programming language. It's a way to in an effective way do something that you might want to do more than one time. Lets say you want to make a function that subtracts two values, but you want to use it for any value. Then you can create a function that takes two parameters and do the calculation...
function sub(x, y)
{
return x-y;
} // Very basic example
In that way you can send any values.
document.createElement('img')
Will simply just create an HTML-tag. In this case an 'img' tag. In your case they want to create one in order to place it inside another element.
Div classes(?) No idea what this is. Any examples?
document.getElementById("something").append.Child('something2')
What this will do is simply take an element by it's id. It can be a DIV or List etc. Then you simply put your element "something2" inside that element. So if something2 is an img, and something is a div. The result would be like:
<div>
<img>
</div>
Onload i.e when the page has being loaded it calls buildImage() function of javascript.This function creates a img tag and appends to the div which is of class 'contents'(Since index is 0 it loads a first image i.e img.src = images[index]).
And once you click on button every 3000 milliseconds its changes the image source to different image based on the index

how to add images to an array in javascript

Hi i found this code online, its for a memory game created in JavaScript,
I want to be able to put images in the array instead of the letters that are there, how do I do it?
Thank You
you must add image source (src) to array, not images.
and if you want to change image , just change src.
<img id="myImage" />
<script>
var x = new Array('1.jpg', '2.jpg', '3.jpg');
var img = document.getElementById("myImage");
img.setAttribute("src", x[0]);
</script>

changing img src inside a a href using javascript

I have the following html:
<li>
<a href=\"p://emotion/appreciate\" onclick=\"flip()\">
<img src=\"smile.png\" />
</a>
</li>
Basically, I want the flip function to replace the src of the img enclosed in it to smile-inactive when pressed, and change it back again to smile.png if it's now already in smile-inactive.png. How can I do this without having to do document.getElementById if I don't want to give the img an id?
Inside your flip function, I would make sure that this points to the anchor you just clicked, then grab the img as the first childNode:
<a href=\"p://emotion/appreciate\" onclick=\"flip.call(this)\">
function flip(){
var img = this.children[0];
if (/smile\.png/.test(img.src))
img.src = "smile-inactive.png";
else
img.src = "smile.png"
}
EDIT
As #am not i am points out, you can achieve a slight gain in browser support by switching
var img = this.children[0];
to
var img = this.getElementsByTagName("img")[0];
Take both images, merge them to one, and just use offset to determine which one is shown.
You can do it by simply by CSS.

Categories