课程: JavaScript Practice: Events
Solution: Add button text on click
- [Instructor] In this challenge, our task is to add a click event to the button in the HTML provided. As part of the click event, we will be adding text to the button that reads, I've been clicked. We only need to worry about adding the click event to the button. The actual simulation of clicking the button has been taken care of for us in the test code. The click event is a mouse event, and one of the most common types of events that we will handle as JavaScript developers. Let's get started with the solution by hopping over to line 10 and the function buttonTextOnClick. This function takes the argument of document. On line 12, we will start by capturing the button element as a variable. Let's call this button buttonToClick and we're going to set it equal to the button that was in the HTML provided. And this button has an ID of btn. So we're going to use the method getElementById and use the document that was provided as an argument here to our function. So document.getElementById and we will pass that in the ID of button or btn. All right, right below where we defined our button to click, let's go ahead and add our event listener click. So we're going to apply this event listener to our button addEventListener. The addEventListener takes a few parameters and for the purposes of this course, we're only concerned about the required ones, type and listener. Type is the type of event to listen for. So in our case, we're listening for the click event. So let's go ahead and pass that in as the first argument here. So click. All right, the next thing that we will need to pass, the next argument is the listener. And the listener is what receives the notification when an event of the specified type has occurred. In this course, we will be using functions to handle our listener events. So let's go ahead here on line 14, the second argument. We're going to pass in a function and just for now, we're just going to set the function up and then we'll go ahead and add some different elements to make sure our button click is executing what we need. For this challenge, we know that we want to add some button text when the button is clicked, so we need to reference our button that we've captured, and then we need to add some inner HTML to that button when the click event occurs. So we'll go ahead and use our buttonToClick and we're going to use the property innerHTML. We'll use this to add that text that we need once the button's been clicked. So this innerHTML is going to be set to I've been clicked. And that's it. That's all we need for this particular challenge. When the button's clicked, we're going to add that text I've been clicked to the button. So let's go ahead and run it and take a look at our solution. Excellent. So you can see when the button was clicked that I've been clicked text was added to the button. Great work.