how to show random images when when click on button using javascript - javascript

I am new to javascript so don't have that much knowledge of js so I have requirement of generate random images when click on button, images are displaying using php(codeigniter framework) how to show random images on every click like a.jpg should come first sometimes last or b.jpg should come first or last
<img src="<?=base_url('assets/game/a.jpg')?>" style="width:120px;"><br>
<img src="<?=base_url('assets/game/b.jpg')?>" style="width:120px;"><br>
<img src="<?=base_url('assets/game/c.jpg')?>" style="width:120px;"><br>
<img src="<?=base_url('assets/game/d.jpg')?>" style="width:120px;"><br>
<img src="<?=base_url('assets/game/e.jpg')?>" style="width:120px;"><br>
<button class="btn btn-success clk_btn" onclick="myfunction">generate random imgaes</button>

Here is an example, just replace the div with your images, also you might want to change the numbers based on the amount of pictures.
function random () {
const randomNr = Math.random()*100;
const elements = document.querySelectorAll('div');
elements.forEach((el) => el.style.display = 'none')
if (randomNr < 34) {
elements[0].style.display = 'block';
} else if(randomNr < 64) {
elements[1].style.display = 'block';
} else {
elements[2].style.display = 'block';
}
}
div {
display: none;
}
<div>image1</div>
<div>image2</div>
<div>image3</div>
<button onclick="random()">switch</button>

You can try this code.
// Javascript
var images = [
"<?=base_url('assets/game/a.jpg')?>",
"<?=base_url('assets/game/b.jpg')?>",
"<?=base_url('assets/game/c.jpg')?>",
"<?=base_url('assets/game/d.jpg')?>",
"<?=base_url('assets/game/e.jpg')?>"
];
document.getElementById("my_button").addEventListener("click", function() {
document.getElementById("my_image").src = images[Math.floor(Math.random()*5)%5]
})
<!-- HTML -->
<button id="my_button">Generate random image</button>
<br>
<img id="my_image" style="width:120px;"/>
Documentation:
Math.random() - JavaScript | MDN
Math.floor() - JavaScript | MDN

A possibility is to hide all images by adding a "hidden" attribute and on the click, choose a random one and remove that "hidden" attribute ;)
let images = document.getElementsByTagName('img');
for(let i = 0; i < images.length; i++)
images[i].setAttribute('hidden', true);
function myfunction()
{
let images = document.getElementsByTagName('img');
for(let i = 0; i < images.length; i++)
images[i].setAttribute('hidden', true);
let rand = Math.floor(Math.random()*images.length);
images[rand].removeAttribute('hidden');
}
<img src="http://via.placeholder.com/350?text=A" style="width:120px;"><br>
<img src="http://via.placeholder.com/350?text=B" style="width:120px;"><br>
<img src="http://via.placeholder.com/350?text=C" style="width:120px;"><br>
<img src="http://via.placeholder.com/350?text=D" style="width:120px;"><br>
<img src="http://via.placeholder.com/350?text=E" style="width:120px;"><br>
<button class="btn btn-success clk_btn" onclick="myfunction()">generate random imgaes</button>
<p id="result"></p>

Related

How do I update the HTML when a button is clicked (change image when button is clicked)?

I'm trying to update the HTML when a button is clicked.
I have tried to solve this issue for a few hours now and I don't know if I'm stupid, but the images are not changing.
const slider = document.querySelector(".slider")
const btn = document.querySelector(".next")
const btn2 = document.querySelector(".previous")
const images = ['car.jpg', `left.jpg`]
window.addEventListener("load", iniliatizeSlider())
function iniliatizeSlider(){
var x = 0
cars = ''
cars += `<div class="slide">
<img src="${images[x]}" alt"client">
<br><br>
</div>`
slider.innerHTML = cars;
}
btn.addEventListener("click", consoleMsg)
btn2.addEventListener("click", consoleMsg2)
function consoleMsg(){
x=1
}
function consoleMsg2(){
x=0
}
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br />
<div class="slider"></div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client" />
</button>
<button class="next">
<img src="right.jpg" alt="next client" />
</button>
</div>
</div>
</div>
</div>
</section>
I was expecting the image to change when the button was clicked, but the image stayed the same, but the value of x changed.
Your initialize function is running once, when the page loads and at that point you are setting the image source to 0 and you never change it after that. You need to adjust the image source within the functions that react to button clicks. Now you do update x in those functions but nothing is ever done with x after that point.
A couple of other things... With .addEventListener(), you pass a reference to the callback function, not invoke the function, so the line should be: window.addEventListener("load", iniliatizeSlider) <-- no () after the function name.
Also, you don't need to replace the HTML on the page to update the image, you only need to update the image's src property.
See comments below:
// Get a reference to an existing image element.
// No need to recreate the <img> element.
const img = document.querySelector(".slider img");
const next = document.querySelector(".next");
const prev = document.querySelector(".previous");
const images = ["https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg", "https://play-lh.googleusercontent.com/VC7rta8PIK3MqmQG5c-F5CNJQ6cCv6Eb-kyBoUcQ2xj83dZVhn7YCj_GIWW8y7TnAMjU=w240-h480-rw"];
let currentIndex = 0; // Keeps track of which image is shown
next.addEventListener("click", function(){
// Check to see if we're at the end of the array
if(currentIndex === images.length-1){
currentIndex = 0; // Reset index
} else {
currentIndex++; // increase the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
prev.addEventListener("click", function(){
// Check to see if we're at the beginning of the array
if(currentIndex === 0){
currentIndex = images.length-1; // Reset index
} else {
currentIndex--; // decrease the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
img { width:50px; }
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br >
<div class="slider">
<!-- Here, we just put a static image element with the first image we want to see. -->
<img src="https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg">
</div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client">
</button>
<button class="next">
<img src="right.jpg" alt="next client">
</button>
</div>
</div>
</div>
</div>
</section>
Call the function initializeSlider() on click of btn instead of consoleMsg().

How i can change img source ? souppose i have 10 images to change on same source

I want to make a button that simply change photo src from given src of image
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="Avatar" >
</div>
I have new1.JPG to new6.JPG photo which should be changed on this image source on click of a button
All photos are in my /img/ folder
And here is my HTML code for the button to change src with onclick.
<button id="changeimg" > Change </button>
As #Teemu said (in comments), if you have the list of the new images you want to change to, you can do it by js code.
<div id="main_photo">
<img class="card-img-top" id="mainImage" src="/img/new0.JPG" alt="Avatar" >
</div>
<button id="changeimg" onclick="changeImage()"> Change </button>
<script>
var imageIndex = 0;
var imageCount = 6; // Can be also an array of images names ["/img/new0.JPG", "/img/new1.JPG", ..., "/img/new6.JPG"]
function changeImage() {
var imageContainer = window.getElementById("mainImage");
imageContainer.src = "/img/new" + (imageIndex++) + ".JPG";
// Make sure you validate the counter so it won't overflow
}
</script>
I have a demo for you if you have the list of images. And I believe that you can have that by simple code to get all images in your local folder.
const listSources = [
'/img/new0.JPG',
'/img/new1.JPG',
'/img/new2.JPG',
'/img/new3.JPG',
'/img/new4.JPG',
'/img/new5.JPG',
'/img/new6.JPG',
]
var currentIndex = 0;
$('#changeimg').click(function() {
// increase index to show the next image
currentIndex++;
// reset if reach the last image
if (currentIndex == listSources.length) currentIndex = 0;
// set image src
$('#main_photo>img').first()
.attr('src', listSources[currentIndex])
.attr('alt', listSources[currentIndex]); // change alt to show changes in demo
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeimg">Change</button>
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="/img/new0.JPG">
</div>

Cannot set property 'src' of undefined at HTMLImageElement.changeImg [duplicate]

This question already has answers here:
Can multiple different HTML elements have the same ID if they're different elements?
(17 answers)
Closed 2 years ago.
In this code when I use [i] it does not work but if I use [0] or [1] instead of [i] it works.
I do not understand why [i] is not working with src.
HTML code
<div class="player">
<p >Player 1
</p>
<img id="myimg" src="images/dice6.png">
</div>
<div class="player">
<p> Player 2
</p>
<img id="myimg" src="images/dice6.png">
</div>
JS code
var images = ["images/dice1.png","images/dice2.png","images/dice3.png","images/dice4.png","images/dice5.png","images/dice6.png"];
for (var i = 0; i < document.querySelectorAll("#myimg").length; i++){
document.querySelectorAll("#myimg")[i].addEventListener("click", changeImg);
function changeImg(){
var randomNumber1 = Math.floor(Math.random() * images.length);
document.querySelectorAll("#myimg")[i].src = images[randomNumber1] ;
}
}
Don't use ID's double they had to be unique. Better use classes instead.
Edited Version
In the eventListener call a function for your changeImg. There get the random Image and use `this`to get the actual element and change the source.
Note: Because random in JS is not really random I added to search as long random as the image is the same like actual. Otherwise you had sometimes to click multiple for a change.
For testing it's better to see if you use the full_page link (in the upper right corner of the output window).
var images = ["https://media.flaticon.com/dist/min/img/home/kiranshastry.png","https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png","https://assets.pokemon.com/assets/cms2/img/pokedex/full/030.png"];
for (let i = 0; i < document.querySelectorAll(".myimg").length; i++){
document.querySelectorAll(".myimg")[i].addEventListener("click", changeImg);
}
function changeImg(){
let randomNumber1;
do {
randomNumber1 = Math.floor(Math.random() * images.length);
} while (this.src == images[randomNumber1]);
this.src = images[randomNumber1] ;
}
<div class="player">
<p >Player 1</p>
<img class="myimg" src="https://www.pokewiki.de/images/thumb/d/d5/Sugimori_848.png/250px-Sugimori_848.png">
</div>
<div class="player">
<p> Player 2</p>
<img class="myimg" src="https://assets.pokemon.com/assets/cms2/img/pokedex/full/034.png">
</div>

How could I optimise this js event?

I am trying to change the img src based on what button I have clicked.
My current approach is to add event listeners to each img id and change then change the image of the top img tag. The issue with this apporach is that I will have a lot of repetetive code especially when im adding more buttons.
So i would like someone to give advice or show me a different and better approach to do this. Im requesting help in only native javascript. Thanks.
document.getElementById("human").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/human.png";
})
document.getElementById("dwarf").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/dwarf.png";
})
document.getElementById("elf").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/elf.png";
})
<img id="imageChange" src="dir/images/human.png" alt="">
<div class="buttonContainer">
<img src="../dir/images/race/human_male.png" id="human" class="race human_container"></img>
<img src="../dir/images/race/dwarf_male.png" id="dwarf" class="race dwarf_container"></img>
<img src="../dir/images/race/elf_male.png" id="elf" class="race elf_container"></img>
</div>
You are right, that having multiple event handler is not a good solution. You can have single one attached to the common container. Something like this:
document.querySelector(".buttonContainer").addEventListener("click", e => {
if (e.target.tagName === 'IMG') {
document.getElementById('imageChange').src = e.target.src
}
})
.buttonContainer img {
height: 30px;
width: 30px;
}
<img id="imageChange" src="https://cdn2.iconfinder.com/data/icons/oxygen/64x64/mimetypes/unknown.png" alt="">
<div class="buttonContainer">
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/4-64.png" id="human" class="race human_container" />
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/6-64.png" id="dwarf" class="race dwarf_container" />
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/29-64.png" id="elf" class="race elf_container" />
</div>
It is necessary to check event target e.target.tagName === 'IMG' because click event bound like this might get triggered by clicking on elements other than images (so with no src).
Since you already know what you want to change the image to why not add it in the html as a data- attribute then just replace the current src with the data- value?
var clickables = document.querySelectorAll('.race');
function showImage(e) {
var src = e.target.src;
document.getElementById('imageChange').src = src;
}
for (var i = clickables.length - 1; i >= 0; i--) {
clickables[i].addEventListener('click', showImage);
}
.buttonContainer img {max-width: 100px}
<img id="imageChange" src="https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG" alt=""/>
<div class="buttonContainer">
<img src="https://vignette.wikia.nocookie.net/nyancat/images/f/ff/Mexinyan.gif/revision/latest?cb=20150409011153" id="human" class="race human_container"/>
<img src="http://www.nyan.cat/cats/original.gif" id="dwarf" class="race dwarf_container"/>
<img src="https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG" id="elf" class="race elf_container"/>
</div>
var imageNodes = document.getElementsByClassName("race");
for(var i = 0; i < imageNodes.length; i++){
imageNodes[i].addEventListener('click', (e) =>{
const imageId = e.target.id;
document.getElementById('imageChange').src = 'dir/images/' + imageId + '.png';
})
}

Image change on currently hovered image based on class name - JavaScript

I'm trying to build a function with pure JavaScript to change an image source of currently hovered over image from a set of images with the same class. Nothing happens with the following code:
<section id="imgs">
<div class="boundary">
<img class="cage" src="cage.png" height="150px" />
</div>
<div class="boundary">
<img class="cage" src="cage.png" height="150px" />
</div>
<div class="boundary">
<img class="cage" src="cage.png" height="150px" />
</div>
<div class="boundary">
<img class="cage" src="cage.png" height="150px" />
</div>
</section>
And my JavaScript function:
<script language="JavaScript">
var x = document.getElementsByClassName("cage");
for (var i = 0; i < x.length; i++) {
x[i].onMouseOver = function () {
this.src = "cageF.png";
}
}
</script>
you need to take care of case sensitivity, use onmouseover instead of onMouseOver
var x = document.getElementsByClassName("cage");
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function () {
this.src = "cageF.png";
}
}
Demo
I understand you have answer to your question. Have a look on below links to understand JavaScript better.
JavaScript case-sensitive
JavaScript is case-sensitive and uses the Unicode character set.
JavaScript mouseover event

Categories

Resources