+ 3
Update element with array value
I am new to coding and I am a self-taught learner. I am creating a web page to test some of the fundamentals and I need help. https://code.sololearn.com/WiddP095NGkb/#html In the code I have an array of phrases, I want the paragraph element to update with a random phrase after a few seconds. Any and all help is greatly appreciated. THANK YOU to everyone that helped! I really appreciate it!
7 Réponses
+ 3
You don't need id to your paragraphe, until you have more than once <p> element in your code...
You can reach your goal by just moving the quote random selection inside the setInterval callback function:
setInterval(function() {
// selects random quote
let randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
$("p").text(randomQuote);
}, 1000);
+ 1
Hi Shawna
Good start.
You will need to add an ID to the Paragraph with <p id="message">
and then you can use document.getElementById('paragraphid').innerHTML="your phrase";
hope this gets you going.
+ 1
Mike Choy :
I don't like jQuery and I widely prefer using vanilla JS (even for more complex selectors, I prefer the .querySelector() and .querySelectorAll() built-in ways since they are widely cross-browser supported), but fix of OP's code only required to move the 'randomQuote' variable assignation inside the setInterval callback function ^^
+ 1
Thank you @visph and @MikeChoy for your help. I fixed the code.
Also, could you explain why I needed to nest the randomQuote variable inside the setInterval method for the code to work???
+ 1
@visph you've been very helpful. Thank you. I tried your suggestion without the variable declaration and it worked with less lines of code.
0
Hi @visph
Just noticed the jQuery in the code, in which case your code is more appropraite
0
You don't need to declare the variable inside the setInterval callback function, but you could, and almost, you need to compute a new value for it each time the function is called ;)