Trying to get multiple elements to load with random positioning - javascript

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';
}
}```

Related

Put links in images that are located in <script>

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>

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);

Assign values from array to a HTML element using javascript or jquery

In my HTML i have 4 image tags like this
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
in my JS file i have this function which picks 4 random values between 1-12 and pushes them into a global array.
function generateCrystalNumber(){
for (var i = 0; i<4; i++){
crystalNumvar = Math.floor(Math.random()*12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
How do I go about assigning each of the values in the array to a different image tag using javascript or jquery ?
Use .each() function and loop over your images, add attribute using data-*
You can get rid of the array and generate random numbers within the .each() function.
function getRandomInt() {
return Math.floor(Math.random()*12) + 1;
}
$(document).ready(function () {
$('img').each(function () {
$(this).attr('data-crystal', getRandomInt());
});
});
var crystalNumbers = [];
function generateCrystalNumber() {
for (var i = 0; i < 4; i++) {
crystalNumvar = Math.floor(Math.random() * 12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
generateCrystalNumber();
$(document).ready(function () {
$('img').each(function (index) {
$(this).attr('data-crystal', crystalNumbers[index]);
})
$('img').on('click', function(){
console.log($(this).attr('data-crystal'));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgContainer">
<img id="crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id="crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id="crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id="crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
function generateCrystalNumber(){
var crystalNumbers = [];
for (var i = 0; i<4; i++){
crystalNumvar = Math.floor(Math.random()*12) + 1;
crystalNumbers.push(crystalNumvar);
}
document.getElementById('imgContainer').childNodes.forEach(function(elm){
elm.value = crystalNumbers.shift();
});
}
generateCrystalNumber();
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
// To associate a random number in image's data attribute
$('img').each(function(){
$(this).data('data-random-Number', generateCrystalNumber());
}
function generateCrystalNumber(){
//for (var i = 0; i<4; i++){ -- For loop is not needed
return (Math.floor(Math.random()*12) + 1);
// crystalNumbers.push(crystalNumvar);
//}
}
I think you are looking for a solution where on clicking the image, you want to show a random image due to random number generation.
Below code can be a start.
Code gets image elements references and pushed them to imgElems array.
It calls generateCrystalNumber() so that random numbers are generated and stored in the array
Click event is registered on imgContainer which is a parent div for all the elements.
Inside event handler, the code figures out which image was clicked and changes the src attribute by reading from the random number array.
Note: You may want to tweak the logic further to reset the random numbers as per your requirements
$(document).ready(function () {
var crystalNumbers = [];
var imgElems = [];
var path = "assets/images/crystal";
imgElems.push(document.getElementById('crystal1'));
imgElems.push(document.getElementById('crystal2'));
imgElems.push(document.getElementById('crystal3'));
imgElems.push(document.getElementById('crystal4'));
generateCrystalNumber();
function generateCrystalNumber() {
for (var i = 0; i < 4; i++) {
var crystalNumvar = Math.floor(Math.random() * 12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
$('body').on('click', '#imgContainer',function (e) {
var id = e.target.id;
$('#' + id).attr('src', path + crystalNumbers[id.slice(-1)-1] + ".jpg");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>

If else statements to check and see if a certain img tag is appended to div wont execute

I need to check if a div called 'ContainterTwo' has either an image with the class 'hd' or 'tl' appended to it, but my if else block never get executed. The images are html img tags inside an array called 'image'. I use a random generator to stimulate a coin flip.
$(document).ready(function(){
var image = ['<img src="heads.jpg" class="hd" height="50" width="50">', '<img src="tails.jpg" class="tl" height="50" width="50">'];
$('#flip').on('click', function(){
var heads = 0;
var tails = 0;
var numToFlip = parseInt($('#number').val().trim());
for(var x = 0; x < numToFlip; x++)
{
var ran = Math.round(Math.random() * (1)) + 0;
$('.ContainerTwo').append(image[ran]);
if($('.ContainerTwo').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
}
})
})
try this,
if($('.ContainerTwo').find('img').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').find('img').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
You can check the random value of variable ran.
I have added some code refactor and removed unnecessary variables and moved jQuery variable declarations out of the loop to improve performance.
Code:
$(document).ready(function () {
$('#flip').on('click', function () {
var heads = 0,
tails = 0,
numToFlip = parseInt($('#number').val().trim()),
$spOne = $('.spOne'),
$spTwo = $('spTwo');
for (var x = 0; x < numToFlip; x++) {
var ran = Math.round(Math.random() * (1)) + 0;
(ran === 0) ? $spOne.html(++heads): $spTwo.html(++tails);
}
});
});
Notice that have been removed the image variable because you are doing: $('.ContainerTwo').append(image[ran]); and after that you are doing $('.ContainerTwo').empty();
You can check if multiple class exists with the is() function. You can check all your .ContainerTwo class with each() and compare with your own variable. Try below
var containerTwo = $('.ContainerTwo img'); //All img in your element
containerTwo.each(function(i,e){ //Check all img in all containerTwo element in page
if($(this).is('.hd, .tl')){ // If .hd or tl found
console.log($(this).attr("class"))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ContainerTwo">
<img class="hd" src="http://img.freepik.com/icones-gratuites/instagram-logo_318-84939.jpg?size=338c&ext=jpg"/>
<img class="tl" src="http://img.freepik.com/icones-gratuites/facebook-logo-bouton_318-84980.jpg?size=338c&ext=jpg"/>
<div>
<div class="ContainerTwo">
<img class="hd" src="http://img.freepik.com/icones-gratuites/instagram-logo_318-84939.jpg?size=338c&ext=jpg"/>
<img class="tl" src="http://img.freepik.com/icones-gratuites/facebook-logo-bouton_318-84980.jpg?size=338c&ext=jpg"/>
<div>

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