Java Reference
In-Depth Information
Instead, we can use a non-blocking approach and set an event listener that will listen out
for any clicks on the page. Every time this event occurs, a callback function will be called.
So the program can continue processing the rest of the code while it is waiting for the click
event to occur.
The following can be used to attach an event listener to the document that fires when the
user clicks anywhere on the page:
document.body.addEventListener("click", doSomething);
Event listeners are added to elements on the page and are part of the DOM API that we
met in the last chapter . In the example, the event listener has been added to the document's
body element. It will call the function doSomething when any part of the page is clicked
on. Until that happens, the program will continue to run the rest of the code.
Note: Clickety Click
The click event occurs when a user clicks with the mouse, presses the
Enter key, or taps the screen, making it a very useful all-round event cover-
ing many types of interaction.
Inline Event Handlers
The original way of dealing with events in the browser was to use inline event attributes
that were added directly into the markup. Here's an example that adds an onclick event
handler to a paragraph element:
<p onclick="console.log('You Clicked!)'">Click Me</p>
The JavaScript code inside the quote marks will be run when a user clicks on the paragraph.
This method will still work in modern browsers, but it isn't recommended for a number of
reasons:
• The JavaScript code is mixed up with the HTML markup, breaking the concept of
unobtrusive JavaScript, which says that any JavaScript code should be kept out of
the HTML.
• Only one event handler can be attached to an element.
 
Search WWH ::




Custom Search