Javascript - Can someone please explain this code - javascript

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

Related

How to make a photo appear when clicking on another photo? Javascript, DOM

I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.

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");

Onclick event - MULTIPLE CLICKS

I'm building a site and I wish to have an image that once clicked it is replaced by another image and, on a second click, replaced by a third image an so on.
I've written a JavaScript function for this. The problem is that I can only call out one item on my index list, it never allows me several clicks to go trough all of my index items.
This is the code I've written so far:
function change (index) {
var links = new Array();
links[0] = img/videoplace.jpg;
links[1]="img/hiroshima.jpg";
var image = document.getElementById('social');
image.src = links[index];
}
<div class="box box1">
<img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)" >
</div>
Writing in the Html <img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)"> just causes the image to be replaced by the one corresponding to change(1) on first click.
Really appreciate any help that can be given.
Attach the event handler properly using Javascript instead (inline handlers are widely considered to be poor practice, and they're difficult to manage). Then, in the Javascript, you can keep a persistent variable of the current image index that's being displayed. On every click, increment the index, and display the appropriate image:
const links = [
'img/beehive.jpg', // first image is already displayed when page is loaded
'img/videoplace.jpg',
'img/hiroshima.jpg'
];
let index = 0;
const img = document.querySelector('#social');
img.addEventListener('click', () => {
index++;
img.src = links[index];
});
Note that declaring an array all at once is often nicer and more concise than using new Array() and assigning to indicies one-by-one.
If you want the displayed images to wrap around so that, once the last image is clicked on, the first image is displayed again, then use modulo. Instead of
index++;
do
index = (index + 1) % links.length;

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

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"]

Preloading and changing images with JavaScript

I'm trying to make some basic image slider as a part of JS excersises, and I've noticed something weird when I ran this script.
The source of an image stored in array under the 0 index is changing when I'm trying to change source image in html code with 'setAttribute' method, so when I want to get back from fifth image to one, this proto-slider (nothing is sliding at the moment) is stuck at second image.
My files are named 0.jpg - 5.jpg.
I've preloaded the images to be displayed smoothly without flicker and I'm displaying one image after the page loads, and then I'm trying to change source of this image to source of next image in array of images. Is this the right way to do it?
Here's the code:
var images = new Array(5);
var i=0;
function addImages(){
for (var j=0;j<images.length;j++){
images[j] = new Image();
images[j].src = j+".jpg";
console.log(images[j].src);
}
var article = document.getElementById("article");
article.insertBefore(images[0], document.getElementById("nav"));
}
function next(){
if (i<images.length-1){
document.getElementsByTagName('img')[0].setAttribute('src',images[++i].src);
console.log(images[0].src);
}}
function prev(){
if (i>0){
document.getElementsByTagName('img')[0].setAttribute('src', images[--i].src);
console.log(images[0].src);
}
}
What is the best way to do such a this as dynamically changing image sources?
I've thought about this:
article.removeChild(document.getElementsByTagName("img")[0]);
article.insertBefore(images[++i], document.getElementById("nav"));
I want to know if this isn't considered as a bad practice and what are the other ways to do it in single line of code.
Thanks in advance and sorry for grammar mistakes.
You could just insert empty image
<img id="someid">
and then use document.getElementById("someid").src=images[0].src
If you'd like to be sure that images[0] is completely loaded, use onload function, like:
images[0].onload=function()
{
document.getElementById("someid").src=images[0].src;
}

Categories