Javascript - How to select an image loaded from an array - javascript

So, I have four images that I put on the page from an array using a loop. Now I have the four images on the page, but I am looking for a way to allow the user to click on any of the images and display a large version of whichever one they click. I was thinking of using a new empty array, using push? to store the clicked image, but I don't know how to click on the images (because I 'm not using an img tag) and load the one that is clicked.
var arrayarray= [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg"
];
var clicked =[];
function asdasd (){
for (var i = 0, j = arrayarray.length; i < j; i++) {
var fmg = document.createElement('img');
fmg.setAttribute("src", arrayarray[i]);
fmg.setAttribute("class", "fmss");
container.appendChild(fwfw);
if (??){
clicked.push(i);
}
}
}

You could add onClick event to an image node.
Selecting the image logic is handled by onClick function. In my example selectedImage variable stores the selected url.
See working example:
const images = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
];
let selectedImage = null;
const result = document.getElementById('result');
const container = document.getElementById('container');
const onClick = function() {
selectedImage = this['data-url']; // or this.src
// just for showing output in html
result.innerText = selectedImage;
};
// on Init
for (let i = 0; i < images.length; i++) {
const fmg = document.createElement('img');
fmg.setAttribute("src", images[i]);
fmg.setAttribute("class", "fmss");
fmg.setAttribute("alt", images[i]);
fmg.onclick = onClick;
fmg['data-url'] = images[i];
container.appendChild(fmg);
}
.fmss { border: 2px solid black; margin: 10px; }
.result { margin: 20px; }
Click me
<div id="container"></div>
<div id="result"></div>

No array needed. Just set the src of the big picture the to src of the clicked picture.
let main = document.getElementById("main"); // Get reference to main image
// Set up click event handler on thumbnail container
document.addEventListener("click", function(event){
// Check to see if the clicked element is a thumbnail
if(event.target.classList.contains("thumb")){
main.src = event.target.src; // Set main picture to match the thumbnail
}
});
.thumb { width:40px; }
#main { width:125px; }
<div id="picContainer">
<img src="https://spectator.imgix.net/content/uploads/2015/06/Emoji.jpg?auto=compress,enhance,format&crop=faces,entropy,edges&fit=crop&w=620&h=413" class="thumb">
<img src="https://i.pinimg.com/originals/43/7b/9b/437b9bbf3fde6d6a331b52bf6c422850.jpg" class="thumb">
<img src="https://cdn3.volusion.com/ghfyz.wgnwv/v/vspfiles/photos/LOF-A3-3650-2.gif" class="thumb">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQisqxRpIXDaOgpdYoy_4UgSKLjaFXM6qIEa4zAOjFIsh_Plp5R" class="thumb">
</div>
<img id="main" src="">

Related

Assign array of image elements to DOM ids

I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.
v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\"
onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";
That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.
Thoughts?
I just grabbed some images off google images. You can use this to refer to the current element.
<img
src='https://osu.ppy.sh/forum/images/smilies/50.gif'
onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"'
onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"'
/>
Edit..
This will change the image when you hover on anything with a "hoverme" class name.
(function() {
var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif";
var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png";
var myimg = document.getElementById('myimg');
myimg.src = img1;
var hoverables = document.getElementsByClassName('hoverme');
for (var i = hoverables.length; i--;) {
hoverables[i].addEventListener("mouseover", hoverMe, false);
hoverables[i].addEventListener("mouseout", unhoverMe, false);
}
function hoverMe() {
myimg.src = img2;
}
function unhoverMe() {
myimg.src = img1;
}
})();
<img class='hoverme' id='myimg' />
<p class='hoverme'>poooooooop</p>
<div class='hoverme'>This si a diiiiivvvvv</div>
The best way to accomplish that is to use CSS.
HTML
<img id="NavIcon">
CSS
#Navicon {
background-image: url(image1.jpg);
}
#NavIcon:hover {
background-image: url(image2.jpg);
}

Random image click

So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.
function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}
Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?
You can try to select the image who have the wanted source.
And add a class or id to your paragraph for readability.
document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};
Example
document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
document.getElementById("rep").innerHTML="you win !";
}
img{
height:100px;
width:100px;
}
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">
<script type="text/javascript" >
var images = document.getElementsByTagName('img');
//find all paragraphs
var paragraphs = document.getElementsByTagName('p');
//define function called on click
function changeParagraph() {
//change first paragraph if exists
if(paragraphs.length) {
paragraphs[0].innerHTML = 'I have been changed!';
}
}
/*
for(var i = 0; i < images.length; i++) {
//set onclick event to every image
images[i].onclick = changeParagraph;
}
*/
// set onclick to the randomImage
images[randomNumber].onclick = changeParagraph;
</script>
Assuming your first paragraph exists before the user clicks the picture, you can add an onClick element to your img tag. Try something like this, changing the URL obviously for your own picture:
<p id = "first">You haven't found Waldo
</p>
<img id = "waldo" src = https://pbs.twimg.com/profile_images/561277979855056896/4yRcS2Zo.png
onclick = "addparagraph()"
/>
JavaScript:
function addparagraph(){
document.getElementById("first").innerHTML = "you found Waldo!";
}

Multiple Id's calling on same JavaScript function

I am trying out a JavaScript where it takes Id of an image and onclick of the image it performs some function. But I have multiple Id's of same image where the id of the onclick'ed image should be processed by JavaScript and the operation should be performed.
Problem is I am not able to get the right id based on the click.
here is my code
1)myhtml
<div class="col-md-3 col-sm-6">
<div class="sub-process-block quantity">
<h3>choose quantity</h3>
<div id="example" onclick="changeImage()">
<img src="img/carton-empty.png" id="myImage">
<img src="img/carton-empty.png" id="myImage1">
<img src="img/carton-empty.png" id="myImage2">
</div>
</div>
2)javascript
<script>
function changeImage() {
var imageArray=["myImage","myImage1","myImage2"];
for(var i=0;i<imageArray.length;i++ ){
image = document.getElementById(imageArray[i]).onclick;
}
if(image.src.match("selected")) {
image.src="img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
Why don't you add an event listener to your images in JS? Then you can check if it's selected or not and update the source accordingly
// get all images and put them in an array
var images = [].slice.call(document.querySelectorAll('img'));
// loop through images and add event listener
images.forEach(function(image) {
image.addEventListener('click', onImageClick);
});
// on click, check if image is selected and update src
function onImageClick(e) {
var image = e.target;
if (image.src.match("selected")) {
// is selected, now unselected it and update src
image.setAttribute('src', 'img/carton-empty.png');
} else {
// is not selected, now select it and update src
image.setAttribute('src', 'img/carton selected.png');
}
}
https://jsfiddle.net/0qzdsf8r/4/
Inspect the image elements in the dev tools and see the class and src change.
Try this ;)
function changeImage(){
var imageArray = ["myImage", "myImage1", "myImage2"];
for(var i = 0; i < imageArray.length; i++){
var image = document.getElementById(imageArray[i]);
if(image.src.match("selected")){
image.src = "img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
}
You placed condition outside for loop;

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

Categories