Adding Hyperlinks to Images in a JavaScript Random Images Array - javascript

I have a random image generating array and I am hoping to insert hyperlinks associated with each image but I can't seem to find an answer or solution that works; or that I can understand enough to adapt to my situation/code. I am a javascript novice just trying to learn as much as I can as I go! Thanks in advance to any help, all is appreciated!
JS as follows:
var random_images_array = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
HTML:
<div id="heroImage" style="text-align: center">
<script type="text/javascript">getRandomImage(random_images_array, 'img/heroImage/')</script>
</div>

Here's what I think you're trying to accomplish. Note: don't use document.write -- that has very specific uses and this isn't a good one. Rather use the innerHTML property (and there are other ways too). I modified the code so you could see the result in the snippet.
let random_images_array = [{
img: "https://picsum.photos/200/300?1",
link: "https://google.com"
},
{
img: "https://picsum.photos/200/300?2",
link: "https://yahoo.com"
},
{
img: "https://picsum.photos/200/300?3",
link: "https://loren.picsum.com"
}
];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
path = ''; // JUST FOR S.O. TESTING
let num = Math.floor(Math.random() * imgAr.length);
let img = path + imgAr[num].img;
let imgStr = `<a href='${imgAr[num].link}'><img src="${img}" alt="" border="0" /></a>`;
document.querySelector('#heroImage').innerHTML = imgStr;
}
window.addEventListener('DOMContentLoaded', () => {
getRandomImage(random_images_array, 'img/heroImage/')
})
<div id="heroImage" style="text-align: center">
</div>

picsum answers GETs from picsum.photos/width/height by redirecting to a random image with the requested dimensions.
In order to have the image and the link match, you must make the picsum GET request and get the redirect URL from the response "Location" header. That's the URL that should be placed in the DOM.
After running the snippet, right-click the image and open it in new tab. Note the same image appears. Using the original GET url as the href will direct user to a new random image.
// super simple promise-returning http request
async function get(url) {
return new Promise(resolve => {
const xmlHttp = new XMLHttpRequest();
xmlHttp.addEventListener("load", () => resolve(xmlHttp));
xmlHttp.open("GET", url);
xmlHttp.send();
});
}
async function getRandomImage(width, height) {
const url = `https://picsum.photos/${width}/${height}`;
let res = await get(url);
// this is the important part: we need the redirect url for the image
const redirectURL = res.responseURL
const html = `<a href='${redirectURL}' target='_blank'><img src="${redirectURL}" alt=""/></a>`;
const el = document.querySelector('#heroImage')
el.innerHTML = html;
}
getRandomImage(200, 300)
<div id="heroImage" style="text-align: center">
</div>
Notice that we don't need to fool around with a random pick from an array of URLs. picsum does the randomizing on the initial GET.

Related

I have problem with add image using javascript array

I would like to add an image to a website using a javascript array. I found a code and then I tried to change it. But i can't get it to work. My code does not display the image on the site.
Code I found:
const imageOut = document.querySelector('.image-out');
for (let key in images) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'images/' + key + '.png';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const images = {"JD-03-128" :{},"JD-05-128": {},"JD-07-128": {},"JD-11-128": {},"JD-12-128": {},"JD-13-128": {},"JD-15-128": {}};
My code:
var imageOut = document.querySelector(".image-out");
for (let key in a) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'image/'+key+'.jpg';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const a = {"a":{},"b":{},"c":{},"d":{},"e":{},"f":{},"g":{}};
image my code: jpg, name absolutely match, name folder absolutely match with folder in my code.
where is my problem ?
If you want to append (add) multiple images to an HTML document using an array, then you can do something like below.
const rootElement = document.getElementById('root')
const array = [
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/id/238/200/300',
'https://picsum.photos/id/239/200/300'
]
array.forEach((src) => {
const imageElement = document.createElement('img')
imageElement.src = src
rootElement.appendChild(imageElement)
})
img{margin:5px}
<div id='root'></div>
Explanation
So basically I'm creating an <img src='' /> element for every item in the array. The items in the array are the url (src) of the images. Those are added as an attribute to the imageElement like so imageElement.src = src and finally they are appended as a child of rootElement

Merge duplicate URLs into 1 URL, Javascript

I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>

What is the best way to change images based on the last 3 characters on the URL?

What is the best way to change images based on the last 3 characters on the URL?
I have 3 pictures but when click - needs to stay as the selected image,
but the page refreshes and goes back to original image
<script type="text/javascript">
function image_swap() {
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3)
if (URLChar("NSW"); image.src = "../MCFILES/NSW1.jpg"
if (URLChar("VIC"); image.src = "../MCFILES/VIC1.jpg"
if (URLChar("QLD"); image.src = "../MCFILES/QLD1.jpg"
} else {
image.src = "../MCFILES/NSW1.jpg"
}
}
function newDocNSW() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=NSW");
}
function newDocQLD() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=QLD");
}
function newDocVIC() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=VIC");
}
</script>
<body>
This is the images i need to change when on hover and when click
runs another script to change URL.
When the page refreshes i need the option to have change picture
when page refreshes to change the URL
<img id="image_swap" src="../MCFILES/NSWO.jpg"
onclick="newDocNSW()"
onmouseover="this.src='../MCFILES/NSW1.jpg';"
onmouseout="this.src='../MCFILES/NSWO.jpg';">
<img id="image_swap" src="../MCFILES/QLDO.jpg"
onclick="newDocQLD()"
onmouseover="this.src='../MCFILES/QLD1.jpg';"
onmouseout="this.src='../MCFILES/QLDO.jpg';">
<img id="image_swap" src="../MCFILES/VICO.jpg"
onclick="newDocVIC()"
onmouseover="this.src='../MCFILES/VIC1.jpg';"
onmouseout="this.src='../MCFILES/VICO.jpg';">
</body>
</html>
This line will only extract a single character
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3 )
If you want the last three characters then use this:
var URLChar = $(location).attr('href').substring($(location).attr('href').length - 3, $(location).attr('href').length);
A much simpler plain/vanilla JavaScript approach would be:
var URLChar = location.href.substring(location.href.length - 3, location.href.length);
Your if conditions are also syntactically incorrect. Here's how it should be:
if (URLChar === "NSW"){
image.src = "../MCFILES/NSW1.jpg";
} else if (URLChar === "VIC"){
image.src = "../MCFILES/VIC1.jpg";
} else if (URLChar === "QLD"){
image.src = "../MCFILES/QLD1.jpg";
} else {
image.src = "../MCFILES/NSW1.jpg";
}
I think this should do if I'm understanding the problem correctly.

How do I change an image with javascript without an onclick event?

I'm trying to get a dummy username and profile picture to display at random, at a random interval. I also want the usernames to match their respective profile pictures.
I currently I have html that displays the usernames correctly
<p id="usr"></p>
<img id="changeimage" src="" alt="Profile picture">
And javascript like this
var players = ['player1', 'player2', 'player3']
var playerpics = ['player1.jpg', 'player2.jpg', 'player3.jpg'];
var activeuser;
var playerpicker = function (activeuser) {
usr.innerHTML = players[activeuser];
changeimage.innerHTML = "<img src='" + playerpics[activeuser] + "' />";
};
setInterval(function () {
var oneintwelve = Math.floor(Math.random() * 12);
if (oneintwelve === 3) {
activeuser = Math.floor(Math.random() * 3);
playerpicker(activeuser);
};
}, 1000);
I know I'm doing something wrong with implementing the new IMG tag, forgive me if I'm not doing this the best way, I'm fairly new to this. Thanks for the help.
You're almost there, you can change the src attribute of an image. Also you didn't quite correctly selected the elements.
var playerpicker = function (activeuser) {
document.getElementById("usr").innerHTML = players[activeuser];
document.getElementById("changeimage").src= playerpics[activeuser];
};
Check this link, it will help you learn http://www.w3schools.com/jsref/dom_obj_select.asp

Display random image with fitting link

I'm using the below code to show random images which works fine. How can I add to this code so that each image gets it's own link? I.e. if "knife.png" is randomly picked I want it to have a link that takes the user to "products/knife.html" and so on.
Thanks for any help!
<div id="box">
<img id="image" /></div>
<script type='text/javascript'>
var images = [
"images/knife.png",
"images/fork.png",
"images/spoon.png",
"images/chopsticks.png",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
Generalize your list of images so that that it can be multi-purposed - you can add additional information later. Then surround the image by an anchor tag (<a>) and use the following.
<div id="box">
<a name="imagelink"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images = ["knife","fork","spoon","chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "images/"+images[x]+".png";
document.getElementById('imagelink').href="products/"+images[x]+".html";
}
</script>
randImg();
Try doing something like this example. Like all these other guys have said, it's better to store this info in a database or something, but to answer your question, put the values you need into an object in the array and reference the properties of the object instead of just having a string array.
<div id="box">
<a id="a"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"http://www.dansdata.com/images/bigknife/bigknife1280.jpg", Href:"http://reluctantgourmet.com/tools/cutlery/item/267-chefs-knife-choosing-the-right-cutlery" },
imageUrlPair = { ImgSrc:"http://www.hometownsevier.com/wp-content/uploads/2011/01/fork.jpg", Href:"http://eofdreams.com/fork.html" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/9/92/Soup_Spoon.jpg", Href:"http://commons.wikimedia.org/wiki/File:Soup_Spoon.jpg" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/6/61/Ouashi.jpg", Href:"http://commons.wikimedia.org/wiki/Chopsticks" },
]
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;
}
randImg();
</script>
Surround the img with an a
<img id="image" />
Then add
document.getElementById("link").href = images[x].replace(".png",".html");
The .replace is a bit crude, but you get the idea.
You can use a convention based approach. In this case the convention is that each product, will have an associated image at "/image/[product]/.png" and a page at "products/[product].html"
<div id="box">
<a id="link"><img id="image" /></a></div>
<script type='text/javascript'>
var products = [
"knife",
"fork",
"spoon",
"chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "/images/" + products[x] + ".png";
document.getElementById('link').setAttribute("href", "products/" + products[x] + ".html");
}
randImg();
this is a very naive approach that won't scale very well. for example, if you have a list of products that changes frequently, or, you need to keep track of the number of available units. a more robust approach would be to store information about your products in a database, and a page that displays the data about a given product (a product detail page), and then use a data access technology to fetch a list of products for display in a product list page (similar to what you have here, except the list of products isn't hardcoded) and then each product would link to the product detail page.

Categories

Resources