I have a function that runs a random word generator on my index.html page, it works just fine however it continues to run when you're on any other page as well (because of windows.onload).
I am unsure how to write javascript to say "only run this function on index.html, no other page" or "just on this class"
window.onload = function refreshWord()
setInterval(function randomWord() {
const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist'];
const randomGenerator = Math.floor(Math.random() * words.length);
document.getElementById('textswap').innerHTML = words[randomGenerator];
}, 2000);
<div class="col">
<h4>These are the words, a <span class="front-page-text-swap" id="textswap"> person </span>.</h4>
</div>
My end goal is to have the function refreshWord()
execute only on the index.html page and no other however I'm at a loss at how to do that (and I'd like to use vanilla js, not jQuery)
Check to see if the pathname
is index.html
, and if it is, create the interval:
if (window.location.pathname === '/index.html') {
setInterval( ...
}
It would also be nice to only select textswap
once, rather than every time the interval runs, and to only create one words
array, rather than declare a new array every time:
if (window.location.pathname === '/index.html') {
const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist'];
const getRandomWord = () => words[Math.floor(Math.random() * words.length)];
const textswap = document.getElementById('textswap');
setInterval(() => {
textswap.textContent = getRandomWord();
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments