I am new to this and need help please. I have a variable in my javascript file that I wanted to respond to a button in my HTML file. Once the button is clicked I wanted my button to call the variable and a new message would appear.
The goal of the project is to generate a new random message once the button is clicked.
here is the javascript below
const messages = [
"Hello!",
"How are you doing today?",
"Have a great day!",
"What's up?",
"Hope you're doing well!",
"Take care!",
"Enjoy your day!",
"Stay positive!",
"Sending you good vibes!",
"Smile and be happy!",
"Did I do this right?",
"I wonder",
"Hello World",
"Hey There",
"Elijah is awesome",
"arrays are powerful",
"Javascript is really hard",
"HTML and CSS are easy"
];
// Function to generate a random index
function getRandomIndex(array) {
return Math.floor(Math.random() * array.length);
}
// Generate a random message
function generateRandomMessage() {
const randomIndex = getRandomIndex(messages);
const randomMessage = messages[randomIndex];
return randomMessage;
}
// Call the function to generate a random message
const randomMessage = generateRandomMessage();
console.log(randomMessage);
var newContent = randomMessage;
var contentHolder = document.getElementById('content-holder');
contentHolder.innerHTML = newContent;
<p id="content-holder">
</p>
<button ondblclick="newContent">click</button>
I tried using the "onclick" attribute but had no success
I tried using the getElementById with no success maybe I’m not doing it right?
I tried googling it and ended up where I started…LOST
Im not sure what to try, I am just starting my coding journey and am lost. Can someone please help?
2
Answers
Just put the part of posting a message in a function
You only have to rearrange your code a little bit.