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

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>

Related

How I can change this deprecated code document.write for improve pagespeed

I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>
There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);
the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.
Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>

How to fill one array value with image AND text? - HTML/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];
}

multi upload images in same sequence as user input

I have a multi-upload for image files, and the problem that I used to face was that the images are appearing in a different sequence as the user's input. For example, user selects Img1, Img2, Img3, Img4. The sequence that it appears might be Img2, Img4, Img3, Img1.
This causes a problem as I have to link them to a text field (image description), and each text field has to match the right image. I did some digging and found out that i can use this code here to make sure that it is being uploaded in the same sequence:
html
<input id="uploadfiles" multiple="multiple" name="photos" type="file">
javascript
$("#uploadfiles").change(function(){
imgpreview(document.getElementById('uploadfiles').files);
});
function imgpreview(files) {
var count = 0;
for (var i = 0, f; f = files[i]; i++) {
(function () {
var div = $("<div></div>");
var reader = new FileReader();
$(".display").append(div);
reader.onload = function(e) {
div.append("<img id='photocount" + count + "' src='" + e.target.result + "' style='height:40px;width:auto;'></img>");
count++;
};
reader.readAsDataURL(f);
}());
}
}
It is also available in fiddle here: https://jsfiddle.net/L3d1L9t3/1/
This javascript code here ensures that the images are appearing in sequence. However, the id for the images are still not in order. For example, if 4 images are uploaded, the ids should be photocount0, photocount1, photocount2, photocount3 respectively. But this is not the case when i inspect element on each of the images.
How do i ensure that the "count" is in sequence as well? This is important since i need to match the count to the text field (image description) as well ["image 1" is paired with "image description 1", "image 2" is paired with "image description 2" and so on]
Use URL.createObjectURL(file) instead it's both faster and easier since it's sync - you don't have to encode/decode back and fort to/from base64 then
$("#uploadfiles").change(function() {
// imgpreview(document.getElementById('uploadfiles').files); <-- not needed
imgpreview(this.files)
})
function imgpreview(files) {
var url, div, len = files.length
var $display = $(".display")
for (var i = 0; i < len; i++) {
url = URL.createObjectURL(files[i])
div = $('<div>')
$display.append(div)
div.append("<img id='photocount" + i + "' src=" + url + " style='height:40px;width:auto'>")
}
}

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

How would I capture the 'alt' attribute for the images a user selects from this slideshow?

How can I modify this script to capture the 'alt' attribute for the images a user selects in a slideshow?
This code displays a series of 20 pairs of images and asks users to select their preferences. Each time the user clicks one of the 'Select' buttons, the 'manipulateDOM()' function advances to the next set of items in the the text and image arrays. However, since it's not set up as a typical form field, I'm having difficulty figuring out how to capture the value of each selection so that it can be submitted to the database with the rest of the form values.
I tried creating a function with the click() method to (at the very least) capture the src value, but I can't get the syntax right so that it can run in conjunction with the 'manipulateDOM()' function. I'd also much rather capture the 'alt' attribute, but I couldn't figure out how to do that.
Function I was experimenting with:
$(document).ready(function () {
$("#buttons").click(function () {
var imgvalue = $("#imgtrendy").attr("src");
$("#picval").text(imgvalue);
document.write(imgvalue + ', ');
});
});
Existing Code:
Javascript - manipulateDOM() and manipulateDOM1() functions
var NumberOfImages = 3 - 1; //-1 because array members starts from 0
var trendy = new Array(NumberOfImages);
trendy[0] = "files/set1/A1.jpg";
trendy[1] = "files/set1/B1.jpg";
trendy[2] = "files/set1/C1.jpg";
var imgNumber = 1; //array key of current image
var NumberOfImages = 3 - 1;
var classic = new Array(NumberOfImages);
classic[0] = "files/set1/A2.png";
classic[1] = "files/set1/B2.jpg";
classic[2] = "files/set1/C2.jpg";
var classicNumber = 1;
var text = 3 - 1;
var text = new Array;
text[0] = "Which would you be more likely to wear?"
text[1] = "Which look is more you?"
text[2] = "Which would you rather wear?"
var textNumber = 1;
function manipulateDOM() {
changeObjects();
NextImage();
}
function changeObjects() {
document.getElementById("question").innerHTML = text[textNumber];
}
function NextImage() {
if (imgNumber < NumberOfImages) //Stop moving forward when we are out of images
{
imgNumber++;
document.images["taste"].src = trendy[imgNumber];
document.images["taste1"].src = classic[imgNumber];
textNumber++;
document.getElementById["question"].innerHTML = text[textNumber];
document.getElementById["selectButton"].innerHTML = text[textNumber];
}
}
function manipulateDOM1() {
changeObjects();
NextImage1();
}
function NextImage1() {
if (imgNumber < NumberOfImages)
{
imgNumber++;
document.images["taste"].src = trendy[imgNumber];
document.images["taste1"].src = classic[imgNumber];
textNumber++;
document.getElementById["question"].innerHTML = text[textNumber];
document.getElementById["selectButton"].innerHTML = text[textNumber];
}
}
HTML
<form id="taste" name="taste" method="post" action="taste-exec.php" >
<h2 id="question"> Which would you be more likely to wear?</h2>
<table><tr>
<td><img id="imgtrendy" src="files/set1/A1.jpg" name="taste" value="trendy[1]" /></td>
<td><img id="imgclassic" src="files/set1/A2.png" name="taste1" value="classic[1]" /></td></tr>
<tr id="buttons">
<td><img id="trendyButton" alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM()"></td>
<td ><img id="classicButton" alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM1()"></td>
</tr><tr>
<td id="picval"></td>
<td><input name="answer" id="answer" type="text" /></td>
</tr></table>
</form>
You get the alt attribute using also the attr method and alt as parameter, just like you are already doing with src. You could try:
function changeObjects() {
document.getElementById("question").innerHTML = text[textNumber];
var imgvalue = $("#imgtrendy").attr("alt");
$("#picval").text(imgvalue);
}
Edit: Example of keeping data in one single array
//to save it
var alt = $("#imgtrendy").attr("alt");
var fileName= 'someValue';//populate accordingly
var myArray[index] = alt + '|' + fileName;
//to retrieve it
var bothValues = myArray[index].split('|'); //gives you an array
alt = bothValues[0] //contains alt at index 0
fileName = bothValues[1] //contains fileName at index 1

Categories