How to fill one array value with image AND text? - HTML/Javascript - javascript

On my website I'm displaying an image which i styled with css to be a card. With a hover effect you can flip the card (frontside is the image) and read an image description on the back side. Further I added a button "Shuffle" which replaces the image with a new one selected random out of an array.
My problem: If the new image is selected, the image description of course stays the same. Is it somehow possible to not only connect the image to an array value but also the fitting text for the description as every image needs an individual description? (Code at the bottom)
Thanks!
<body>
<div class="maincontainer">
<div class="thecard">
<div class="thefront">
<img src="images/meme1.jpg" id="picture1"/>
</div>
<div class="theback">Picture1 Description</div>
</div>
</div>
<button onClick="shuffle();">SHUFFLE</button>
<script type="text/javascript">
function shuffle(){
var images1 = [],
index1 = 0;
images1[0] = "images/meme2.jpg";
images1[1] = "images/meme3.jpg";
images1[2] = "images/meme4.jpg";
index1 = Math.floor(Math.random() * images1.length);
document.getElementById("picture1").src = images1[index1];
}
</script>
</body>

Instead of just storing the image URL in an array, store the URL and the description in objects and put the objects into an array:
function shuffle(){
var images1 = [];
images1.push({url:"images/meme1.jpg", description: "meme 1"});
images1.push({url:"images/meme2.jpg", description: "meme 2"});
images1.push({url:"images/meme3.jpg", description: "meme 3"});
images1.push({url:"images/meme4.jpg", description: "meme 4"});
images1.push({url:"images/meme5.jpg", description: "meme 5"});
var index1 = Math.floor(Math.random() * images1.length);
console.log(images1[index1].url, images1[index1].description);
}
shuffle();
shuffle();
shuffle();
shuffle();
shuffle();
shuffle();

Instead of storing only the images, you can store the description too. In this case you need to make an array of objects: this is how it is supposed to look like:
let images = [
{
src: './image.png', //source of the image
description: 'This is an image' //Description of the image
}
]
Then shuffle this array just like you shuffled the old array.

function shuffle(){
var images1 = [], descriptions = [],
index1 = 0;
images1[0] = "images/meme2.jpg";
images1[1] = "images/meme3.jpg";
images1[2] = "images/meme4.jpg";
descriptions[0] = "Picture2 Description";
descriptions[1] = "Picture3 Description";
descriptions[2] = "Picture4 Description";
index1 = Math.floor(Math.random() * images1.length);
document.getElementById("picture1").src = images1[index1];
document.getElementsByClassName("theback")[0].innerText = descriptions[index1];
}

Related

I Need these images to have links what am I doing wrong?

right guys this is driving me crazy will someone just tell me straight how to make these images links to pages such as test1.html,test2.html,test3.html and rather than tell me what to change just paste the entire fixed code so that i can test it im new to javascript and hate it
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[1] = "frames/1.png";
randomImage[2] = "frames/2.png";
randomImage[3] = "frames/3.png";
randomImage[4] = "frames/4.png";
randomImage[5] = "frames/5.png";
randomImage[6] = "frames/6.png";
randomImage[7] = "frames/7.png";
randomImage[8] = "frames/8.png";
randomImage[9] = "frames/9.png";
randomImage[10] = "frames/10.png";
//loop to display five randomly chosen images at once
for (let i=0; i< 1; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number].src +'" style="width:450px" />';
}
}
<button onclick="getRandomImage()">Show Image</button>
<div class="container">
<span id="result" align="center"></span>
</div>
For the link, you'll want to associate your image and link together, assuming that each link has a specific image to be associated with. So let's update your random images and well also need to surround the img tag with an anchor tag, something like:
randomImage[1] = {
src: "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg",
href: "/index1.html"
}
// update the rest of the links accordingly, then:
'<img src="'+ randomImage[number].src +'" style="width:450px" />'
(updated per comment)
You need to enclose the image in the tag.
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[2] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[3] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[4] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[5] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[6] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[7] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[8] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[9] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[10] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
//loop to display five randomly chosen images at once
for (let i=0; i< 1; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="width:450px" />';
}
}
move the array outside the function
shuffle the array
take the first 5
wrap in A
function fy(a, b, c, d) { // https://stackoverflow.com/a/25984542/295783
c = a.length;
while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}
// declare an array to store the images AND their href
const images = [{
src: "https://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg",
href: "aaa.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2018/01/cute_dogsurprise_petsworld.jpg",
href: "bbb.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2016/09/dogs-300x200.gif",
href: "ccc.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2018/01/dog-hates-stairs-BF0505-001-resized-56a26a793df78cf772755e08-1024x682.jpg",
href: "ddd.html"
}, {
src: "https://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg",
href: "eee.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2018/01/cute_dogsurprise_petsworld.jpg",
href: "fff.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2016/09/dogs-300x200.gif",
href: "ggg.html"
},
{
src: "https://www.petsworld.in/blog/wp-content/uploads/2018/01/dog-hates-stairs-BF0505-001-resized-56a26a793df78cf772755e08-1024x682.jpg",
href: "hhh.html"
},
]
document.getElementById("show").addEventListener("click", function() {
fy(images);
document.getElementById("result").innerHTML = images.slice(0, 5).map(img => `<img src="${img.src}" style="width:450px" />`).join("")
})
<button type="button" id="show">Show Image</button>
<hr/>
<!--image displays here-->
<span id="result" align="center"></span>
You can use document.createElement() rather than using innetHTML
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[2] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[3] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[4] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[5] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[6] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[7] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[8] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[9] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
randomImage[10] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; //i need this image here to be a link
//loop to display five randomly chosen images at once
for (let i = 0; i < 1; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random() * randomImage.length) + 1;
//print the images generated by a random number
const link = document.createElement('a')
link.target = '__blank__';
link.href = randomImage[number];
const img = document.createElement('img');
img.src = randomImage[number];
link.appendChild(img);
document.getElementById("result").appendChild(link);
}
}
<button onclick="getRandomImage()">Show Image</button>
<!--image displays here-->
<span id="result" align="center"></span>

Button Click Audio Start and Stop JS

Wondering how to stop the current audio and have a new one start? Right now the audio overlays each other and it can get very jumbled. I currently have an array of random audio that plays. However, if you click the buttons in quick succession the audio will overlap. I am not opposed to having the button be unclickable until the audio stops as well.
<script type = "text/javascript">
//Create random picture array
function imgchange() {
var myImages1 = new Array();
myImages1[1] = "Matthew1.jpg";
myImages1[2] = "Matthew2.jpg";
myImages1[3] = "Matthew3.jpg";
myImages1[4] = "Matthew4.jpg"; //Image Array
myImages1[5] = "Matthew5.jpg";
myImages1[6] = "Matthew6.jpg";
myImages1[7] = "Matthew7.jpg";
var rnd = Math.floor(Math.random() * myImages1.length); // Random Choice of Image
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd]; //Gets Image
}
function playRandomSound() {
//An array to house all of the URLs of your sounds
var sounds = [
new Audio("Sound1.mp3"),
new Audio("Sound2.mp3"),
new Audio("Sound4.mp3")];
//This line will select a random sound to play out of your provided URLS
var soundFile = sounds[Math.floor(Math.random() * sounds.length)];
soundFile.play();
//Find the player element that you created and generate an embed file to play the sound within it
document.getElementById("Button").innerHTML = '<embed src="' + soundFile + '" hidden="true" autostart="true" loop="false" />';
}
</script>
<body style="height: 663px">
<div class="Title" id="title">Alright! Alright! Alright!</div>
<p><img id="gen-img" src="img/who/1.jpg"></p>
<p> <input id="Button" type="button" value="Random" onclick="imgchange(); playRandomSound();"/></p>
</body>
Consider the following code.
$(function() {
function pickRandom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function imgChange() {
var myImages = [
"https://i.imgur.com/dDRchZA.jpg",
"https://i.imgur.com/4ILisqH.jpeg",
"https://i.imgur.com/YkxAggs.png",
"https://i.imgur.com/ZZhIZ9K.jpg",
"https://i.imgur.com/UeLNtOi.png",
"https://i.imgur.com/saWRUwn.png",
"https://i.imgur.com/xM0RWTd.png"
];
$("#gen-img").attr("src", pickRandom(myImages));
}
function playRandomSound() {
var aud;
var sounds = [
"Sound1.mp3",
"Sound2.mp3",
"Sound4.mp3"
];
if ($("audio").length) {
aud = $("audio");
} else {
aud = $("<audio>", {
type: "audio/mp3"
}).css("display", "none").appendTo("body");
}
aud[0].pause();
aud[0].currentTime = 0;
aud.attr("src", pickRandom(sounds));
aud[0].play();
}
$("#Button").click(function() {
imgChange();
playRandomSound();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Title" id="title">Alright! Alright! Alright!</div>
<p><img id="gen-img" src="https://i.imgur.com/xM0RWTd.png" width="640"></p>
<p><input id="Button" type="button" value="Random" /></p>
I would just store the Source in the Array not the Object. Then using HTML5, you can create (and hide) an <audio> tag with all the proper properties. Once created, you can call the DOM Element Methods for .play().
You can use:
aud[0].play();
Or:
aud.get(0).play();
See more: https://api.jquery.com/get/

Get all image src from array of image src and placing them into div with Javascript?

I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>

Appending new container on click

I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

Categories