Using on() for Event Handling2:26 with Treasure Porth
Use jQuery's on() method when handling events for extra flexibility.
So far we've done basic event handling with the click method. 0:00 jQuery also has many other methods for 0:04 other event types such as mouseover, or when a mouse moves over an element. 0:06 Keypress for when a user presses a key in an input element, and 0:11 the focus event, when an input field captures focus, or 0:15 in other words when the cursor appears in an input field. 0:19 These methods are fine for simple applications, but they have their limits. 0:23 For example, 0:27 what if I wanted to add more than one event listener to this button element? 0:28 What if I wanted to reveal the spoiler not only if they click the button but 0:32 if they press Enter or something else? 0:37 I could add another event listener, but 0:39 then I'd be repeating the same code inside each one. 0:42 Takeaway provides a flexible method to solve this problem, the on method. 0:46 The on method looks like this. 0:51 You first pass in the name of the event, click for example, and then the handler. 0:53 You can use on to assign one event handler to multiple events, this way the same 0:59 code will fire when either event occurs, saving you from having to repeat code. 1:04 There are other benefits that we'll look at later. 1:09 Let's refactor some of our code to start to see the full power of the on method. 1:11 If you don't have the spoiler revealer project open from the previous video, open 1:16 the workspace with this video, head down to the click method and replace with on. 1:21 Next we wanna pass in the event name as the first parameter here. 1:27 Event name is click. 1:33 We will leave the handler as is as the second parameter. 1:34 Lets save and preview. 1:38 When we click the button it works the same as it did before. 1:41 The spoiler is revealed and the button is hidden. 1:43 However now we could add another event if we wanted. 1:46 Add a space after the click event and then add mouseleave. 1:50 So let's save and refresh. 1:55 So move your cursor over the button and nothing happens. 1:57 Move your cursor away from the button and the button disappears and 2:01 the spoiler shows. 2:04 Refresh the page, move your mouse over and then click, the handler triggers again. 2:06 As you can see, on is useful if you want some code to fire after one or 2:12 more events. 2:16 Let's get rid of mouseleave for now, as that was just for demonstration. 2:18 In the next video, I'll show you another way the on method can be useful. 2:21
You need to sign up for Treehouse in order to download course files.Sign up