When I click on the image, the image changes randomly, but it happens that some images are repeated after the click. how can I solve it?
Below is my queue.
let h1 = document.querySelector('h1')
let bigSquare = document.createElement('div')
bigSquare.id = 'bigSquare'
h1.after(bigSquare)
let images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg']
let randomImage = function(){
return (Math.round(Math.random()*(images.length-1)))
}
let image = document.createElement('img')
bigSquare.append(image)
image.src = images[randomImage()]
image.onclick = function(event){
event.target.src = images[randomImage()]
}
Just create a variable called say, "randNumb" that stores the random number generated in it and whenever the image is clicked, compare the previous random number with the new one and if they're different, change the img src else run the random image function again.
Check and run the following Code Snippet for a practical example of the above approach:
let h1 = document.querySelector('h1');
let bigSquare = document.createElement('div');
let randNumb = 0;
bigSquare.id = 'bigSquare';
h1.after(bigSquare);
let images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg'];
let image = document.createElement('img');
bigSquare.append(image);
image.src = images[randNumb];
let randomImage = function(){
let x = Math.round(Math.random()*(images.length-1)); // get random number
if (x == randNumb) {
randomImage(); // same random number so run function again
}
else {
randNumb = x;
image.src = images[randNumb]; // not same random number so change src
console.log("The image src right now is: " + image.src);
}
}
image.onclick = function(){randomImage()};
<h1></h1>
Related
I have two arrays.One of videos and one of images. I need to play only one video at a time when image is clicked. Like if clicked on img[1] then it should play video[1] and if img[2] then video[2].
I need to do something like this : IMAGE
I have gone through few examples but didn't find any similar answer using only javascript. Now when i click on image it opens anchor tag link which i have added for testing but not able to play videos.
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
var allVideos = videosList.length;
var i = 0;
for (; i < allVideos; i++) {
var vid = document.createElement('source');
vid.src = videosList[i];
document.getElementById('myVideo').appendChild(vid);
}
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
Here is running code as example:codepen
// JavaScript can be change in the following way
// Assuming that the video to be played is the same as index of the image clicked
// make it as global to access in all functions
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://media.w3.org/2010/05/bunny/movie.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
window.onload = function() {
// for videos
var vid = document.createElement('source');
vid.src = videosList[0]; // playing first video in the array by default
document.getElementById('myVideo').appendChild(vid);
// for images
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
// a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
img.id = i; // for the reference of clicked image
a.appendChild(img);
a.addEventListener("click", clickFn, false);
document.getElementById('myImg').appendChild(a);
}
}
/**click function for the image of the image */
clickFn = function(e){
var video = document.getElementById('myVideo');
video.src = videosList[parseInt(e.srcElement.id,10)];
video.play();
}
Hope it helps ..!!
modified code in codepen
I'm trying to shuffle images from array to a specific div.
<body>
<div id="set"></div>
</body>
<script>
var ArrayOfImages = ['bar.jpg',
'foo.jpg',
'koo.jpg',
'too.jpg'
];
var set = document.getElementById("set");
set.addEventListener("click", randomize, false);
ArrayOfImages.forEach(function(image) {
var elem = document.createElement('img');
elem.src = image;
set.appendChild(elem);
});
function shuffle(array) {
let counter = array.length;
// While there are elements in the array`enter code here`
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function randomize() {
set.innerHTML = shuffle(ArrayOfImages);
}
</script>
Now the problem is, that innerHTML only changes the text of the image but cannot set an src to it. Though it does the shuffle.
Any help would be appreciated!
.innerHTML will change the actual HTML, not the images src which is what you want to change.
At the moment you are getting your image elements from your HTML using
document.getElementById('set)
however, you HTML can only have one element with the id set. Thus, you can use the class attribute instead to give multiple elements the identifier of 'set' and get all your image elements using:
document.getElementsByClassName('set')
which will return a collection of your HTML image tags. Now, to change each image's source you can loop over this collection or loop over your shuffled images and set each image's source.
See an example below for further clarification:
var img_elems = document.getElementsByClassName('set'); // Get all elements to set the image to
// To go into your randomize() function:
// Shuffled images returned via your shuffle() function
var shuffled_images = ['https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350', 'https://www.pandotrip.com/wp-content/uploads/2018/09/Seigantoji-Pagoda-and-Nachi-Falls-in-Nacho-Japan.jpg', 'https://www.elastic.co/assets/bltada7771f270d08f6/enhanced-buzz-1492-1379411828-15.jpg'];
for (var i = 0; i < shuffled_images.length; i++) {
img_elems[i].src = shuffled_images[i]; // Set the image to the src value.
}
/* Ignore this */
img {
height: 200px;
width: 200px;
}
<img src="" class="set" /><br />
<img src="" class="set" /><br />
<img src="" class="set" />
More clean and better way of doing it in vanilla javascript.
The issue was in your shuffle function.
var image_swap_tool = function(options){
var self = this;
self.ArrayOfImages = options.ArrayOfImages;
self.image_container_elem = document.getElementById("set");
self.image_container_elem.addEventListener("click", function(){
self.randomize();
});
}
image_swap_tool.prototype.create_image = function(){
var self = this;
var images = self.ArrayOfImages;
var image_container = self.image_container_elem;
image_container.innerHTML = '';
for(var i=0; i < images.length;i++){
var img = document.createElement('img');
img.setAttribute('src',images[i]);
image_container.appendChild(img);
}
};
image_swap_tool.prototype.shuffle = function(){
var self = this;
var images = self.ArrayOfImages;
let counter = images.length;
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = images[counter];
images[counter] = images[index];
images[index] = temp;
}
//Set new order back to images for next time
self.ArrayOfImages = images;
//Images are shuffled then append them again
self.create_image();
}
image_swap_tool.prototype.randomize = function(){
var self = this;
var image_container = self.image_container_elem;
self.shuffle();
}
var options = {};
options.ArrayOfImages = ['bar.jpg', 'foo.jpg', 'koo.jpg', 'too.jpg'];
var tool = new image_swap_tool(options);
tool.create_image();
Thanks
I'm trying to make a Generator where a user can insert their Battlenet Name (name) and have it output their Emblem (data.characters[2].embemBackground) plus their light level (data.characters[0].light) on the image too.
Then, I want the user to be able to use an image link, such as: http://www.test.com/image.png
And have it get updated automatically with the stats from the API, so it overwrites the image without changing the URL.
Result:
I used html2canvas capture to get the image itself from (#character2img)
I do realize this is probably not the best way to approach this.
Code:
const { Client } = require('destiny2');
const client = new Client('apiKey');
const html2canvas = require('html2canvas');
window.memberName = function(){
var pName = document.getElementById("pageheader");
var pLl = document.getElementById('LightLevel');
var pLl2 = document.getElementById('LightLevel2');
var pLl3 = document.getElementById('LightLevel3');
var gT = document.getElementById('Guardian');
var gT2 = document.getElementById('Guardian2');
var gT3 = document.getElementById('Guardian3');
var divI = document.getElementById('character1img');
var name = document.getElementById('search').value;
client.getProfile(name, '4')
.then(data => console.log(data));
client.getProfile(name, '4').then(data => {
pName.appendChild(document.createTextNode(`${data.profile.displayName}`));
// Character 1
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[0].embemBackground}`;
var image = document.getElementById('character1img').appendChild(elem);
// Light Level
pLl.appendChild(document.createTextNode(`♦ ${data.characters[0].light}`));
// Character 2
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[1].embemBackground}`;
var image2 = document.getElementById('character2img').appendChild(elem);
// Light Level
pLl2.appendChild(document.createTextNode(`♦ ${data.characters[1].light}`));
// Character 3
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[2].embemBackground}`;
var image2 = document.getElementById('character3img').appendChild(elem);
// Light Level
pLl3.appendChild(document.createTextNode(`♦ ${data.characters[2].light}`));
});
}
window.screenshot = function(){
html2canvas(document.querySelector("#character1img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}
window.screenshot2 = function(){
html2canvas(document.querySelector("#character2img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}
window.screenshot3 = function(){
html2canvas(document.querySelector("#character3img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}
var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');
btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');
/* Looping through images */
for(var i=1;i<=5;i++){
var newImage = document.createElement('img');
newImage.setAttribute('src', "images/pic"+i+".jpg");
thumbBar.appendChild(newImage);
}
function getPath(){
var path = this.document.getAttribute('src').value;
}
newImage.onclick=function(){
var path = newImage.getAttribute('src');
console.log(path);
displayedImage.setAttribute('src', path);
}
i tried printing out the path when i click on the image, but it only return the last value of newImage..but i have 4 pictures that can be selected
Why don't you append a CSS class to each of the image elements and use the class name as the CSS selector? Like so,
newImage.className = 'my-class-name';
You'll have to set the event listener inside the loop for each new element. Like this:
var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');
btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');
/* Looping through images */
for(var i=1;i<=5;i++){
var newImage = document.createElement('img');
newImage.setAttribute('src', "images/pic"+i+".jpg");
thumbBar.appendChild(newImage);
// **************************************************
newImage.onclick=function(){
var path = this.getAttribute('src'); // instead of newImage use this
console.log(path);
displayedImage.setAttribute('src', path);
}
// **************************************************
}
function getPath(){
var path = this.document.getAttribute('src').value;
}
Note: If you are planing on using i inside the the function assigned to the onclick then consider taking a look at this.
In one function I have a loop that creates 10 images using the createElement();. In the other function I have another loop that contains info that I need to add text after each picture but my code adds it at the end of all 10 pictures I need them to be after every corresponding picture.
This is the function that displays the text:
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
display.appendChild(span1);
}
}
I cant individually set the id of each image because i created them in js. Thanks for the help in advance and no jquery please
for (var x = 0; x<json.length;x++){
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
display.appendChild(image);
var a = document.getElementById("artist");
var y = document.getElementById("year");
var artist = document.getElementById("artist").selectedIndex;//index of value of the switch statement
var year = document.getElementById("year").selectedIndex;//index of value of the switch statement
var realYear = y[year].text;//Value of the selected text
var realArtist = a[artist].text;//Value of the selected text
var display = document.getElementById("Results");
}
This is my second loop. I want displayalbum to appear after every picture. I cannot combine them because of other complications in the code
Try to do something like that: plunker
function displayAlbum(){
for (var x = 0; x < 10 ; x++){ // change to json.length
var span1 = document.createElement("span");
span1.innerText = 'json[x].album';
span1.id = 'span'+x;
var display = document.getElementById("results");
display.appendChild(span1);
}
}
The loop where you are creating images, give a unique id to image like image.id = "picture" + x;
Then change displayAlbum() function to use corresponding image to place the span tag.
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
var img = document.getElementById("picture" + x); // use unique id of img to access it
if(img.nextSibling) { // if img is not the last node in 'results'
display.insertBefore(span1, img.nextSibling);
} else { // if img is the last node in 'results'
display.appendChild(span1);
}
}
}
You can achieve your goal with single loop and using Figure and FigCaption element , specifically created for this kind of display image with its description
var json = [{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test1"},{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test2"}];
for (var x = 0; x<json.length;x++){
var fig = document.createElement("figure");
var figCap = document.createElement("figcaption");
figCap.innerText = json[x].album;
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
fig.appendChild(image);
fig.appendChild(figCap);
display.appendChild(fig);
}
<div id="results">
</div>