Put links in images that are located in <script> - javascript

I'm new to html, and I also have no idea how to work with js, so can I insert a link in multiple images inside of javascript of an html?
Here is a code that make the image change every time I refresh,
What I need to do is make these image clickable, and leading to another site
Preferably, I'd want to try to make it so that the js can lead to a code in html, so i can also add stuff such as height
<img src="3w.png" alt="car" height="333">
function random_imglink() {
var myimages = new Array()
myimages[1] = "1.png"
myimages[2] = "2.png"
myimages[3] = "3w.png"
myimages[4] = "4w.png"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<img src="' + myimages[ry] + '" border=0>')
}
random_imglink()

Arrays are 0 based so no need to force 1 when 0
Just change the HTML to be a link
It is recommended to not use document.write, so instead insert it into a container
I am using template literals to create the link and eventListener to see when the page has loaded
const myimages = ["1.png", "2.png", "3w.png", "4w.png"]
const links = ["page1.html","page2.html","page3.html","page4.html"];
function random_imglink() {
var ry = Math.floor(Math.random() * myimages.length)
return `<img src="${myimages[ry]}" height="333" border=0/>`;
}
window.addEventListener("DOMContentLoaded", function() {
document.getElementById("linkContainer").innerHTML = random_imglink();
});
<div id="linkContainer"></div>

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

Trying to get multiple elements to load with random positioning

So I'm not super great at JS yet, but I found this code block that does exactly what I need it to do - takes an element and makes it's position random. The problem is this only works if I use getElementById, but I want to do this with about 12 different elements, not just the one.
Ive tried giving them all the same class and using getElementsByClassName, I've tried using querySelector, I've tried querySelectorAll - With each one of these examples the code either doesn't work, or it only works for the first element.
Markup:
<div id="1" class="rando">
<img src="someIMG" alt="logo" itemprop="image">
</div>
<div id="2" class="rando">
<iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</div>
JS:
function getRandomPosition(element) {
var x = document.body.offsetHeight-element.clientHeight;
var y = document.body.offsetWidth-element.clientWidth;
var randomX = Math.floor(Math.random()*x);
var randomY = Math.floor(Math.random()*y);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.getElementsByClassName("rando");
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
I also tried putting these through a loop, but that didn't work either:
function getRandomPosition(element) {
var x = document.body.offsetHeight-element.clientHeight;
var y = document.body.offsetWidth-element.clientWidth;
var randomX = Math.floor(Math.random()*x);
var randomY = Math.floor(Math.random()*y);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.querySelector("#1, #2");
for (var i = 0; i < rpos.length; i++) {
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
}
Any help / direction is, as always, greatly appreciated!
thanks!
You almost had it. In your for loop you operate on the entire HTMLCollection rpos rather than each seperate element. For example what this line rpos.setAttribute("style", "position:absolute;"); does is run setAttribute for this collection of elements, rather than for each element in this collection we should run setAttribute. With a small adjustment you get this:
function getRandomPosition(element) {
var x = document.body.offsetHeight - element.clientHeight;
var y = document.body.offsetWidth - element.clientWidth;
var randomX = Math.floor(Math.random() * x);
var randomY = Math.floor(Math.random() * y);
return [randomX, randomY];
}
window.onload = function() {
const rpos = document.getElementsByClassName("rando");
for (let rpo of rpos) {
rpo.setAttribute("style", "position:absolute;");
document.body.appendChild(rpo);
var xy = getRandomPosition(rpo);
rpo.style.top = xy[0] + "px";
rpo.style.left = xy[1] + "px";
}
};
<div id="1" class="rando">
<img src="someIMG" alt="logo" itemprop="image">
</div>
<div id="2" class="rando">
<iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</div>
<p class="rando">Test A</p>
<p class="rando">Test B</p>
<p class="rando">Test C</p>
In your first example, your getElementsByClassName returns an Array-like collection. Your rpos variable therefore contains something you need to loop over. Loop over rpos and it should work.
Alternatively, in your second example, querySelector only returns the first element corresponding to that selector, so not something you can loop over. Change this to querySelectorAll to get an iterable list.
EDIT: I just noticed your for loop as it stands won't work either. Don't forget that you need to manipulate each element in the list, not the list as a whole.
In the loop in the second example, you need to work on each individual item, something like:
window.onload = function() {
var rpos = document.querySelector("#1, #2");
for (var i = 0; i < rpos.length; i++) {
rpos[i].setAttribute("style", "position:absolute;");
document.body.appendChild(rpos[i]);
var xy = getRandomPosition(rpos[i]);
rpos[i].style.top = xy[0] + 'px';
rpos[i].style.left = xy[1] + 'px';
}
}```

How to delete elements created by CreateElement and AppendChild

[
// Calendar
var calendar = document.getElementById("calendar");
calendar.addEventListener("click",function(){
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
calendar.style.transform = "rotateX(-50deg)";
calendar.style.transformOrigin = "bottom center";
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.parentNode.removeChild("hotdogs");
});
// Hotdog
var hotdog = document.getElementById("hotdog");
var everywhere = document.getElementById("everywhere");
var NumClick4 = 0;
hotdog.addEventListener("click",function(){
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.appendChild(hotdogs);
var x = Math.floor(( Math.random() * 450) + 800);
NumClick4++;
console.log(x + " " + NumClick4);
hotdogs.style.width = "200px";
hotdogs.style.left = x + "px";
if(NumClick4 == 1) {
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
} else {
}
});
<div id="hotdog" class="">
<img src="SVG/hotdog2.svg" alt="hotdog">
</div>
<div id="everywhere"></div>
<div id="calendar">
<img src="SVG/calendar.svg" alt="calendar">
</div>
<div id="factbox">
</div>
enter image description here
Sorry if my code looks messy. So as shown on the image, I want the hotdogs on the sky, which were created by "CreateElement" and "AppendChild" method to disappear using "RemoveChild" method. For example, when I click other elements like "flag", I want the just the new "hotdogs" to disappear. I think I am not getting how it works. I would appreciate advice and tips.
Following line is wrong by 2 counts
everywhere.parentNode.removeChild("hotdogs");
You are trying to remove something which hasn't been added yet
You need to remove the Element rather than string
i.e.
everywhere.parentNode.removeChild(hotdogs);

Refresh function per 3 seconds

function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<h1 class="comingsoon">' + myimages[ry] + '</h1>')
}
random_imglink()
How do you make it so that the above code gets refreshed every 3 seconds? Like, the output is refreshed every 3 seconds. Thanks.
setInterval is easier way for your query.
Simple Example:
setInterval(function(){ alert("Hello"); }, 3000);
Don't use document.write. Use document.innerHTML instead.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
And of course the setInterval, as the other answers suggest.
I've created a fiddle that I think does what you want.
I hope you like cats.
http://jsfiddle.net/alexjamesbrown/9cu5L666/
Note - I'm setting the inner html of a div, rather than the whole document
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "http://placekitten.com/g/100/400"
myimages[2] = "http://placekitten.com/g/200/250"
myimages[3] = "http://placekitten.com/g/300/234"
myimages[4] = "http://placekitten.com/g/500/300"
myimages[5] = "http://placekitten.com/g/100/400"
myimages[6] = "http://placekitten.com/g/430/100"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1;
var div = document.getElementById('myContainer');
div.innerHTML='<h1 class="comingsoon"><img src="' + myimages[ry] + '"</img></h1>'
}
setInterval(function(){ random_imglink(); }, 3000);
You can use setInterval
window.setInterval(random_imglink,3000);
You can use
window.setInterval(random_imglink, 3000);
but be cautious because if your browser does not render the content in the time interval you should expect choppiness and dropped frames. A much better approach is to use requestAnimationFrame
The Window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.body.innerHTML = '<h1 class="comingsoon">' + myimages[ry] + '</h1>';
}
window.setInterval(random_imglink, 3000);

How to choose random image from image set in javascript

I have been using the following code to generate random images, but none of the pictures are showing up.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
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(theImages[whichImage]);
}
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
</body>
</html>
Thank you in advance for your help!
You already have the full <img> tag in the array. So just use:
document.write(theImages[whichImage]);
Although I would advise against using document.write. Of course, in your situation, where it's being executed in the middle of HTML, I don't see much of a problem. It would be bad if document.write were executed after the page was rendered. Normally, the preferred method is something like the appendChild method or even setting innerHTML, although it would take some refactoring to get your code to use them.
Here's an example of how I'd set it up:
(function () {
var theImages = [{
src: "http://www.techinasia.com/techinasia/wp-content/uploads/2009/12/smile.png",
width: "675",
height: "467"
}, {
src: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdcHlJqgIKNOS0DaEjO31xK1zYtmJlza8z70ljiKFbo2ZgLdh9eA",
width: "1084",
height: "732"
}, {
src: "http://cdn2-b.examiner.com/sites/default/files/styles/large_lightbox/hash/68/d1/68d11ab242d40c8d5abbe8edb58fd4ed_0.jpg?itok=M3qtK47_",
width: "200",
height: "200"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
DEMO: http://jsfiddle.net/wFjGv/
This code uses a new object to hold the details for each image. That way, you can easily set and get each image's properties that you need without hardcoding HTML.
It preloads the images in the preBuffer array, and when needed, an image is retrieved from the array, and put into the <body>. You can change its target in the onload event. The getRandomImage function returns a random image from that array. I updated the method of getting a random integer as well.
You are setting an <img src= something that is not what you want. Your array (theImages) is storing full <img> tags, not just the link to that image.
Either change you theImages array to store values like so:
theImages[0] = "/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png"
OR use the current setup as the image tag.
document.write(theImages[whichImage]);
Also:
With random numbers, you should probably stick to Math.floor() lest
you round over your max length.
var j = 0 is missing a ;
theImages img tags are not closed (<img ... />
Try this-
var srcs = [
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png",
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png",
"foo/bar.jpg"
], imgs = [];
function init() {
"use strict";
var i, x, div;
div = document.createElement('div');
div.id = 'imageContainer';
document.querySelector('body').appendChild(div);
for (i = 0; i < srcs.length; i += 1) {
x = new Image();
x.src = srcs[i];
imgs.push(x);
}
}
function showRandom() {
"use strict";
document.querySelector('#imageContainer').innerHTML = imgs[Math.random * imgs.length];
}
init();
To add a random image-
showRandom();
PS - You shouldn't use document.write, but if you do, you should close the stream by document.close, to tell the browser to finish loading the page. Read more - MDN JS Docs

Categories