Onclick event - MULTIPLE CLICKS - javascript

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;

Related

forEach displays only last item from the list

I would like to display some of my data for each item from my list. The problem is that the function is displaying only information about the last item.
Here's how the function looks:
drivers.forEach(addLink);
function addLink(driver, index) {
const nameList = document.getElementById('nameList');
const driverImg = document.getElementById('driverImg');
nameList.href = `?driver=${index}`;
nameList.textContent = driver.name;
driverImg.src = driver.image;
driverImg.height = "45";
list.appendChild(nameList);
list.appendChild(driverImg);
}
It was working when it was creating elements (const nameList = document.createElement('a'); , but I wanted to change that to getElementById
html looks like this:
<nav id="list">
<a id="nameList"></a>
<img id="driverImg">
</nav>
Your function is called addLink but it gets an existing element (with getElementById) and changes it. When you change it multiple times, you end up with the last set of changes you made to it.
If you want to create a link you need createElement.
Since you actually want to add Elements you need to create them like you did before, now you are just getting the same element that allready is on the document and changing it's values (overwrititing the changes from the previous iteration in every iteration)

How can the same button play different videos every time it's clicked?

I'm trying to hack together a video player to play local files in a cool interface, it's literally only ever going to be used by my family so the code doesn't have to be beautiful or anything. I've basically got a table full of DVD covers, and when clicked each one of them is supposed to open a modal with a video player for Chrome.
I've managed to do all of this, except I'm struggling to get it so the same button/image can be pressed and a different video file gets shown. Basically this is what I've got inside every table cell:
<th>
<div class="imageBox">
<div class="imageInn">
<img id="standardDVD" src="images/dvdCover1.jpg" alt="Snow">
<div class="hoverImg">
<img id="buttonPlay" src="images/play.png" alt="play">
</div>
</div>
</div>
</th>
I've then got the following JavaScript code to show the modal when that's clicked (I basically took it from here and modified it to show a video instead):
var playButton = document.getElementById('buttonPlay');
playButton.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
var dvdCover = document.getElementById('standardDVD');
dvdCover.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
(I've got two basically identical ones so it works if either the DVD cover or the button is clicked)
My thinking was to try and somehow get the src of the image (which should be doable if it's the image that's clicked, but I'm not too sure about how to get the dvd cover src if the button is the one getting clicked. From there I was thinking of having a simple (but long) JavaScript if function to convert each DVD cover to the src of the right video file, and simply change the videoToPlay variable used in the modal:
var videoToPlay = "movies/a Movie.mp4";
Edit since I don't think I was clear: I have a table with 55 different DVD covers, each in one cell and each with the identical HTML code except with a different dvdCover1.jpg image. What I'm trying to do is get it so each one plays the correct video, without having to make a new function for each.
I realize this is definitely not best practice, and any suggestions to improve the overall setup are appreciated - although I'm trying to get this together for Christmas and my knowledge of HTML and CSS is basically zero which is why I'm currently going for simplicity: only 5 people will ever see this anyway so best practice isn't necessarily important!
One option is to create an array with all your movies paths:
var videosToPlay = [
"movies/a Movie.mp4",
"movies/movie a.mp4",
"movies/a new Movie.mp4"
];
Then you need to get all handlers like this:
var dvdsCover = document.getElementsByClassName('standard-dvd-class-in-all-table');
Then just define the click event to all of them using the matching index. Your array must match the full table order of DVDs:
[...dvdsCover].forEach((dvdCover, index) => {
dvdCover.onclick = () => {
modal.style.display = "block";
document.getElementById("videoModal").src = videosToPlay[index];
};
});
Hope it helps.

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

onmouseover & onmouseleave functions not working properly

I'm new to this site and relatively new to web development. I was trying to incorporate javascript to this webpage I made with just HTML & CSS. This webpage is basically an online store for certain products and what I was trying to do was that when someone has their mouse over one of the products, it would provide some details such as the name of the product and the price and when they move the mouse out, it would go back to just an image of the product. For some reason, with my code, it will change the elements so that it shows the details but it won't change back to the original image after the mouse moves away.
I've tried everything I could think of and the goal of this project was to make sure I had an understanding of javascript so I was trying to do this without any jquery. Any advice would be greatly appreciated.
Here is the code:
//Holds all div elements with class attribute "productlink" which hold the product images
var products = document.getElementsByClassName("productlink");
//When this function is called, the product image is changed to show an image of the product, the name and price
//classNum - specifc class element being called
//priceAmount - price of product
//describe - Description/Name of the product
function hoverDetails(classNum, priceAmount, describe) {
//Div container for details, image of product, price of product and description
var divContainer = document.createElement("div");
var image = document.createElement("img");
var price = document.createElement("p");
var description = document.createElement("p");
var priceTextNode = document.createTextNode(priceAmount);
var descriptionTextNode = document.createTextNode(describe);
description.appendChild(descriptionTextNode);
price.appendChild(priceTextNode);
image.src = picArray[classNum];
divContainer.setAttribute("class", "newdiv");
image.setAttribute("class", "newimg");
price.setAttribute("class", "itemprice")
description.setAttribute("class", "itemdescription");
products[classNum].parentNode.style.textDecoration = "none";
divContainer.appendChild(image);
divContainer.appendChild(description);
divContainer.appendChild(price);
//This should replace the current image with the details specified eariler
//childNode is set to 1 due to a #text node in the div
products[classNum].replaceChild(divContainer, products[classNum].childNodes[1]);
}
//This function, when called, replaces the detailed product with just an image of the product
function originalImage(classNum) {
var image = document.createElement("img");
image.setAttribute("class", "display_image");
image.src = picArray[classNum];
products[classNum].replaceChild(image, products[classNum].childNodes[1]);
}
Here is the element that is referencing these functions:
<a href="#">
<div class="productlink" onmouseover="hoverDetails(0,'$85.95','Printer') "onmouseout="originalImage(0)">
<img class="display_image" src="images/printer1.jpg" />
</div>
Don't the mind the variable names and I'm sorry if my code seems too much. Any help would be appreciated.
EDIT: Just to let people know, both functions work. The onmouseleave event works when the onmouseover event is not attached. Additionally, the code works when the onmouseover event is replaced with onclick. When I replace onmouseover with onmouseenter, the code works once but never again. This is very strange.
There is actually another mouse event called onmouseout. Add another attribute called onmouseout="removeHoverDetails()" and then inside of removeHoverDetails() select everything and say .visibility = "hidden"; Or whatever way you want to use to get rid of the elements in the popup. Also check out w3schools tutorial on onmouseover and onmouseout: http://www.w3schools.com/jsref/event_onmouseover.asp
Okay I found the solution to my problem. I put the onmouseover event on the image element of the "productlink" div an left the onmouseout event on the div and looks to be working fine.

Javascript Random Clickthrough

I am creating an image which, when you click on it, sends you to one of four links. I have managed to code this, but the problem I am having is that it is completely random (only part of the point). What I would like to be able to do is to randomise the first click through, and then if the user goes back to the image, only leave them with the remaining three destinations, and then obviously two and one at the end. This is to stop them theoretically ending up at the same link every single time and not being able to access the other three.
Does anybody know how I might be able to do this? The code I have currently is:
<img src="IMAGE" onclick="randomLink();">
<script type="text/javascript">
var randomLink = function () {
var links = ["LINK 1","LINK 2","LINK 3","LINK 4",];
var max = (links.length)
var randomNumber = Math.floor(Math.random()*max);
var link = links[randomNumber];
window.location = "http://" + link;
}
</script>
You can simply remove the selected entry from the links array (i.e. using Array.splice). Next time the user clicks the link, you would generate a random number between 0 and 2 only and so on.

Categories