I am working on a website and I have a div with an id. I am using this code to get a certain id div to move randomly. I have tried many things and it has not worked. Code:
// collect all the divs
var divs = document.getElementsById('ad');
// get window width and height
var winWidth = window.innerWidth;
var winHeight = window.innerHeight;
// i stands for "index". you could also call this banana or haircut. it's a variable
for (var i = 0; i < divs.length; i++) {
// shortcut! the current div in the list
var thisDiv = divs[i];
// get random numbers for each element
randomTop = getRandomNumber(0, winHeight);
randomLeft = getRandomNumber(0, winWidth);
// update top and left position
thisDiv.style.top = randomTop + "px";
thisDiv.style.left = randomLeft + "px";
}
// function that returns a random number between a min and max
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
I found It online and I don’t think it works because my edit: Changing the getElementsByType('div')
to getElementsById('ad')
. "ad" is the id I used. Any idea how to get this to work? I need an answer soon because this is a school project.
I tried that code and I expected it to move my ad div to a random location every time the program was run.
2
Answers
As you only want to position a single
<div>
you need to change your code to work with just one result instead of many. You’ve tried to do that by usinggetElementsById
but that isn’t a valid function (in your browser you can use F12 to see the console / dev tools, where it will show an error). Change it togetElementById
to fix it (note I removed the "s").As this is a school project, I won’t write the code for you, but I’ll give you some further hints:
for
loop because you’re only trying to change the position of the single<div>
<div id="ad">
may need the styleposition: absolute;
for the newtop
andleft
values to take effect.There are a few things to take note of:
getElementsById doesn’t exist. To get an element by ID you can use querySelector or getElementById.
Both of those will return a single element so there is no need for a loop.
Also #ad will need to be positioned absolutely.
Also, if you are getting the screen’s width and height, I would recommend subtracting the div’s width and height from the screen’s width and height. That way your div won’t go off the edge of the screen.
For testing purposes, I added a click button so you can keep clicking it to see the div move around. But you don’t need that part.