- Joined
- Sep 24, 2022
- Messages
- 5
- Reaction score
- 0
I'm new to js and have been making my first attempt to cobble together a script to make a background element change position in random increments whenever a link on a web page (that I'm working on) is clicked:
This doesn't throw any errors in console, but it doesn't work either, all that happens is the background "blinks".
if I replace
with:
it shows that the values are being generated OK... so I can only assume there's something wrong with the way I've defined the function to change the background-position value
Would appreciate some advice, thanks!
JavaScript:
const backgroundElement = document.querySelector('.container');
const positionXY = [100, 25, 50, 75];
function randomX(positionXY) {
return positionXY[Math.floor(Math.random() * positionXY.length)]
}
function randomY(positionXY) {
return positionXY[Math.floor(Math.random() * positionXY.length)]
}
document.querySelectorAll("a").forEach(a =>
a.addEventListener("click", () => {
backgroundElement.style.cssText = `background-position: ${randomX}% ${randomY}%;`
}
)
)
This doesn't throw any errors in console, but it doesn't work either, all that happens is the background "blinks".
if I replace
Code:
backgroundElement.style.cssText = `background-position: ${randomX}% ${randomY}%;`
Code:
alert("x position:" + randomX(positionXY));
alert("y position:" + randomY(positionXY));
Would appreciate some advice, thanks!
Last edited: