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
Related
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
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;
I am not good at code so am a bit in the hands of anyone who might be able to help.
I have a functioning Ticker Tape working in my wordpress site here www.solosails.com
currently, it works from data manually entered, I would like to modify it so that it takes the title and link from my RSS feed myurl/feed hopefully by using something like this ...
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
The Java Script code is...
function startTicker(){theCurrentStory=-1;theCurrentLength=0;if(document.getElementById){theAnchorObject=document.getElementById("tickerAnchor");runTheTicker()}else{document.write("Error");return true}}function runTheTicker(){var e;if(theCurrentLength==0){theCurrentStory++;theCurrentStory=theCurrentStory%theItemCount;theStorySummary=theSummaries[theCurrentStory];theTargetLink=theSiteLinks[theCurrentStory];theAnchorObject.href=theTargetLink}theAnchorObject.innerHTML=theStorySummary.substring(0,theCurrentLength)+whatWidget();if(theCurrentLength!=theStorySummary.length){theCurrentLength++;e=theCharacterTimeout}else{theCurrentLength=0;e=theStoryTimeout}setTimeout("runTheTicker()",e)}function whatWidget(){if(theCurrentLength%2==1){return theWidgetOne}else{return theWidgetNone}}
This is the part of the code that potentially needs altering so that the hardcoded links and titles become the new code pulling from the rss feed...
var theCharacterTimeout = 50;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
var theItemCount = 2;
theSummaries[0] = "Solo Sails proudly sponsor Lizzy Foremans Mini Transat Campaign... Read more here ...";
theSiteLinks[0] = "http://www.solosails.com/solo-sails-sponsor-lizzie-foremans-mini-transat-campaign/"
theSummaries[1] = "10% discounts on ALL multiple sail orders !! Try us for price with your new sails, complete our simple quote form here.";
theSiteLinks[1] = "http://www.solosails.com/quotes"
startTicker();
Many thanks in advance if you can help!
Andrew
Still hoping somebody can help here.
I basically want to either get theSummaries and theSiteLinks to be pulled from the rss or change the arrays so that they use the XML parser in Javascript.
Would really appreciate some help here and happy to donate something via paypal for the working result.
Regards, Andrew
Thanks to #David Hammond for finding the answer ...
var theCharacterTimeout = 75;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
jQuery.get('http://www.solosails.com/feed/', function(data) {
var $xml = jQuery(data);
$xml.find("item").each(function() {
var $this = jQuery(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text()
}
//Do something with item here...
theSummaries.push(item.title);
theSiteLinks.push(item.link);
});
theItemCount = theSummaries.length;
startTicker();
});
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.
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.