+ 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!

30th Mar 2018, 4:33 AM
Shawna-Kaye Patten
Shawna-Kaye Patten - avatar
7 Answers
+ 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);
30th Mar 2018, 10:39 AM
visph
visph - avatar
+ 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.
30th Mar 2018, 9:48 AM
Mike Choy
Mike Choy - avatar
+ 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 ^^
30th Mar 2018, 11:59 AM
visph
visph - avatar
+ 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???
30th Mar 2018, 5:26 PM
Shawna-Kaye Patten
Shawna-Kaye Patten - avatar
+ 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.
30th Mar 2018, 5:34 PM
Shawna-Kaye Patten
Shawna-Kaye Patten - avatar
0
Hi @visph Just noticed the jQuery in the code, in which case your code is more appropraite
30th Mar 2018, 11:01 AM
Mike Choy
Mike Choy - avatar
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 ;)
30th Mar 2018, 5:28 PM
visph
visph - avatar