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

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

Related

Adding Hyperlinks to Images in a JavaScript Random Images Array

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.

Trying to pull from a folder of images

Hi first time here and I'm very new to coding
I'm making a website where its kind of an inside joke about nfts (making fun of them just wanted to be clear)
and I got a bunch of randomly generated images that I want to be selected from to show one at random when you click a button
right now I have this
<script type="text/javascript">
ImageArray = new Array();
ImageArray[0] = "https://cdn.discordapp.com/attachments/669350505264447512/912516499862863892/55.png";
ImageArray[1] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516499531522128/52.png';
ImageArray[2] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516499208548432/54.png';
ImageArray[3] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516498898173962/32.png';
ImageArray[4] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516498617171988/44.png';
ImageArray[5] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516498390659082/47.png';
ImageArray[6] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516498138988554/27.png';
ImageArray[7] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516497883152414/11.png';
ImageArray[8] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516497686036520/5.png';
ImageArray[9] = 'https://cdn.discordapp.com/attachments/669350505264447512/912516497459535882/3.png';
ImageArray[10] = 'https://cdn.discordapp.com/attachments/669350505264447512/912517257987518484/70.png';
function getRandomImage() {
var num = Math.floor( Math.random() * 11);
var img = ImageArray[num];
document.getElementById("randImage").innerHTML = ('<img src="' + img + '" width="300px,">')
}
</script>
<button onclick="getRandomImage()";>NFT</button>
<div class="parent" id="randImage" ></div>"
and that works pretty well but I don't want to write ImageArray 1 to 100 for every possible image and was wondering if I could somehow write it to where it pulls from a file of all the images
help would be appreciated and also explain as much as possible because I would like to know how to do similar stuff
https://misinformedmember.000webhostapp.com/
above is the website if it helps

trying to dynamically replace the url from "a href" but javascript is not updating results

I'm trying to replace the urls in the html using javascript but it is not working although when I test it by I "alerting" them the values pop up correctly, but when I publish it and click on the images the new urls are not applied. Any help would be greatly appreciated
Could you please look at the code and tell me what is going on?:
<script>
var rutaBase = "assets/fotos/";
function cambieFotos(cualFoto) {
var listaFotos = ["360.jpg", "foto3.jpg", "mathura.jpg"];
var numFotosLista = listaFotos.length;
var foto1 = document.getElementById("foto1");
var foto2 = document.getElementById("foto2");
var foto3 = document.getElementById("foto3");
for (i = 0; i < 3; i++) {
var fotoAleatoria = listaFotos[Math.floor(Math.random() * numFotosLista)];
var fotoRoll = document.getElementById("foto" + (i + 1));
fotoRoll.src = "assets/fotos/" + fotoAleatoria;
fotoRoll.href = "assets/fotos/" + fotoAleatoria; //this code is not working.
var sacarFotoLista = listaFotos.indexOf(fotoAleatoria);
listaFotos.splice(sacarFotoLista, 1);
numFotosLista = listaFotos.length;
}
}
</script>
<div id="contenedor">
<img id="foto1" onMouseOver="cambieFotos(this)" src="assets/fotos/360.jpg"> <--!this needs to update-->
<img id="foto2" onMouseOver="cambieFotos(this)" src="assets/fotos/foto3.JPG"><--!this needs to update-->
<img id="foto3" onMouseOver="cambieFotos(this)" src="assets/fotos/mathura.jpg"><--!this needs to update-->
</div>
<!--contenedor-->
fotoRoll is an <img>, not the surrounding <a>. You should modify the parent instead:
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;
You're setting the href on the image element, not the hyperlink element. Try something like
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;

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.

Script to display an image selected at random from an array on page load

I'm using a script on the homepage of a website for a photographer which displays an image selected at random from an array. I have found two different scripts which perform this function. I'd like to know which script is preferable and if it has been written correctly or can be improved. I wonder if it is possible to include a function that would prevent the same image from loading twice until all of the images in the array have been used. Thanks for taking a look.
Version 1
<script type="text/javascript">
<!--
var theImages = new Array()
theImages[1] = 'portrait/fpo/01.jpg'
theImages[2] = 'portrait/fpo/02.jpg'
theImages[3] = 'portrait/fpo/03.jpg'
theImages[4] = 'portrait/fpo/04.jpg'
theImages[5] = 'portrait/fpo/05.jpg'
theImages[6] = 'portrait/fpo/06.jpg'
theImages[7] = 'portrait/fpo/07.jpg'
theImages[8] = 'portrait/fpo/08.jpg'
theImages[9] = 'portrait/fpo/09.jpg'
theImages[10] = 'portrait/fpo/10.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="images/'+theImages[whichImage]+'">');
}
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<script type="text/javascript">showImage();</script>
</td></tr>
</table>
Version 2
<script type="text/javascript">
<!--
var ic = 11; // Number of alternative images
var xoxo = new Array(ic); // Array to hold filenames
xoxo[0] = "images/portrait/fpo/01.jpg"
xoxo[1] = "images/portrait/fpo/02.jpg"
xoxo[2] = "images/portrait/fpo/03.jpg"
xoxo[3] = "images/portrait/fpo/04.jpg"
xoxo[4] = "images/portrait/fpo/05.jpg"
xoxo[5] = "images/portrait/fpo/06.jpg"
xoxo[6] = "images/portrait/fpo/07.jpg"
xoxo[7] = "images/portrait/fpo/08.jpg"
xoxo[8] = "images/portrait/fpo/09.jpg"
xoxo[9] = "images/portrait/fpo/10.jpg"
xoxo[10] = "images/portrait/fpo/11.jpg"
function pickRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
// Write out an IMG tag, using a randomly-chosen image name.
var choice = pickRandom(ic);
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<script type="text/javascript">document.writeln('<img src="'+xoxo[choice]+'" >');</script>
</td></tr>
</table>
This code will load images randomly and his respective link to load.
<html>
<head/>
<title>Jorgesys Android</title>
<script type="text/javascript">
var imageUrls = [
"http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
];
var imageLinks = [
"http://www.stackoverflow.com"
, "http://www.reforma.com"
, "http://www.nytimes.com/"
, "http://www.elnorte.com/"
, "http://www.lefigaro.fr/international/"
, "http://www.spiegel.de/international/"
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"Jorgesys Android\"/></a>';
return img;
}
</script>
</head>
<body bgcolor="black">
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>
</html>
Decided to make it an answer.
FYI... You're missing one of your pictures in the first version, fyi.
I would go with 2. 1 is loading all of the images up front (more useful if you'll be changing images, doing a slide-show type thing). So it uses more bandwidth and will make your page load slower.
2 looks fine but I might change pickRandom(ic) to pickRandom(xoxo.length) so you don't have to forget about updating ic as you add more images.
You would probably want either to create a cookie for the user (lastImageIndex) to loop through the items. If cookies aren't available, just use a random image. Otherwise, start at a random image. Then each time accessed with the cookie increment. When you reach the length, go back to 0.
function getCookieValue(choice){
// read cookie here, if found, parseInt(cookieValue,10) and assign to choice
// Then return choice (either original value or updated)
return choice;
}
var choice = pickRandom(xoxo.length);
choice = getCookieValue(choice);
// Check if it correspond to an image
if (choice >= xoxo.length) choice = 0;
// Store the cookie here. Store choice++
That description is slightly different than what you asked for, since its per user, but I'd bet it gives you more the result you are looking for.

Categories

Resources