1

If I have a simple button in my html:

<button id="bgnBtn">Start Game</button>

and I want a prompt in my JS:

var userAdjective = prompt("Please provide an Adjective");

to initiate only after the button is clicked, how would I write this?

Can't seem to find this concept out there, at least for one so boiled down to basics like this.

Thanks,

jonah butler
  • 68
  • 1
  • 2
  • 7
  • 1
    Possible duplicate of [addEventListener vs onclick](http://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) – Mike Cluck May 17 '16 at 22:19
  • There's a lot of questions on this but basically you need to add an event handler. – Mike Cluck May 17 '16 at 22:20
  • If you making s game, you could have an HTML input with display:none; and when click on the start game button you can change visibility and get the user input. Why use this instead of prompt, so you can match the design of the input colour borders etc. if you want this solution am sure the answer is already here in stack. – T04435 May 19 '16 at 03:23

3 Answers3

7

Set an onclick handler for the button and then have it trigger a javascript function - note the use of the alert - just to show the functioning of the function:

function promptMe(){
    var userAdjective = prompt("Please provide an Adjective");
    alert (userAdjective);
}
<button id="bgnBtn" onclick="promptMe()">Start Game</button>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
1

I would recommend attaching an event listener to the button in your JS code.

document.querySelector('#bgnBtn').addEventListener('click', function() {
    var userAdjective = prompt("Please provide an Adjective");
    alert (userAdjective);
}

This example uses an anonymous function for handling the click event. You could also do the following:

document.querySelector('#bgnBtn').addEventListener('click', promptMe);

function promptMe() {
    var userAdjective = prompt("Please provide an Adjective");
    alert (userAdjective);
}
Rico Herwig
  • 1,672
  • 14
  • 23
0

If you use an alert box it would look like this: Alert me

<script>
function myFunction() {
  alert("I am an alert box!");
}
</script>
cylso-_-
  • 1
  • 2
  • 1
    Hi, welcome to StackOverflow! The provided answer does not resolve the problem completely. There is a function which displays an alert message. But no information is provided on how to link this JS function to the HTML button. – Pardhu Oct 31 '20 at 20:25