Computer Science

Javascript DOM Events

JavaScript DOM events are actions that occur in the Document Object Model (DOM) of a web page, such as a user clicking a button or hovering over an element. These events can be programmed to trigger specific JavaScript functions, allowing for interactive and dynamic web page behavior. Event handling is a fundamental aspect of web development and is essential for creating responsive and engaging user interfaces.

Written by Perlego with AI-assistance

11 Key excerpts on "Javascript DOM Events"

  • Book cover image for: The JavaScript Workshop
    No longer available |Learn more

    The JavaScript Workshop

    A New, Interactive Approach to Learning JavaScript

    • Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    Linux Terminal would simply read the contents of a directory on the hard disk and display the details of those files and directories within the Terminal window. The Linux operating system is built on the premise of such very small and simple applications working together to create a much larger ecosystem. The converse of this may be modern multiplayer video games, which typically react to user interaction and receive streamed data from remote locations. The former of these concepts can be considered much like a function: input enters from the top and is output somewhere within the body, typically, the end of the function.
    JavaScript applications can facilitate both ends of this spectrum, and indeed, anything in between. Modern browsers are now fully capable of providing the foundations for immense and processor-intensive 3D multiplayer games, responding to data from numerous sources, but JavaScript is also frequently used for the simplest of tasks, such as formatting a string or rounding a number .
    At the core of all of these applications are events . Events, conceptually speaking, are triggers that execute code. This might, for example, be the ready state when a page has finished loading or a mouse event when the user clicks an element within the page. Typically, without events, functions won't know when to execute and, therefore, nothing can happen.
    Throughout this chapter, we will examine the options JavaScript provides for listening to and handling different types of events within the browser environment.

    Event Types

    An event is simply a notification or a "triggered " alert within the JavaScript runtime. These notifications can represent practically anything but are a means to invoke one or more of your own functions when such an event occurs.
    When a web page loads, the browser will typically display content as soon as it is available. This means some content will be presented to the user before the entire page has finished downloading. The browser does this to prevent long-loading assets from withholding other content from being available to the user.
    Now, imagine you want to invoke a function immediately within a web page to rotate an image. JavaScript code embedded into a web page is able to run immediately once it has been parsed by the JavaScript engine, which could possibly be before the image in question is available. To overcome this conundrum, JavaScript provides an onload
  • Book cover image for: JavaScript from Beginner to Professional
    eBook - ePub

    JavaScript from Beginner to Professional

    Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages

    • Laurence Lars Svekis, Maaike van Putten, Rob Percival, Laurence Svekis, Codestars By Rob Percival(Authors)
    • 2021(Publication Date)
    • Packt Publishing
      (Publisher)

    11

    Interactive Content and Event Listeners

    You are now familiar with the basic manipulation of the Document Object Model (DOM ). In the last chapter, we had a look at events, and we saw that event listeners are constantly monitoring for whether a certain event is taking place; when it does occur, the specified event (a function) gets invoked.
    In this chapter, we are going to take this knowledge one step further and use event listeners to create interactive web content. This chapter is really going to complete your DOM knowledge. We are going to cover the following topics:
    • Interactive content
    • Specifying events
    • The onload event handler
    • The mouse event handler
    • The event target property
    • DOM event flow
    • onchange and onblur
    • The key event handler
    • Drag and drop elements
    • Form submission
    • Animating elements
    Note: exercise, project and self-check quiz answers can be found in the Appendix .

    Introducing interactive content

    Interactive content is content that responds to the actions of a user. Think, for example, of a web app in which you can create postcards dynamically, or play a game on a website in a web browser.
    This interactive content is made possible by changing the DOM based on user interactions. These interactions could be anything: entering text in an input field, clicking somewhere on the page, hovering over a certain element with the mouse, or a certain input with the keyboard. All these are called events. We have seen events already. But there is actually more to it!

    Specifying events

    There are three ways to specify events. We have seen each of these in the previous chapter, but let's run through them again now. One is HTML-based and the other two are JavaScript-based. For this example, we are going to use the click
  • Book cover image for: JavaScript
    eBook - ePub

    JavaScript

    Syntax and Practices

    We have now seen most of the properties and methods provided by DOM and how to use them to change the look and feel of the web page. The work done so far is not fruitful unless there is no active response mechanism within the website such as changing colors on the web page on some click, providing an interactive slider that computes on the go, hover over events, automatically play music on page loading and many more. Whatever we have learnt so far, we can do most of these manually, but now we will understand how to do all of this based upon some event such as a mouse click or a key press or the mouse rolling on the web page.
    Events are some actions that occur in a browser either automatically or via user-initiated actions, such as on web page loading, click of a button, form submission, manual keypress, mouse click etc. The mechanism of handling these events is known as event handling. JavaScript provides event handlers and event listeners to assist and execute the event handling mechanism [102] . An event handler is a function that initiates when an event occurs. An event listener attaches a responsive interface to an element, which allows that particular element to wait and listen for the given event to fire.
    The document object contains properties and methods related to event handlers such as animation, drag and drop, clipboard, full screen, load and unload, keyboard, pointer, selection, transition and touch. The list of event handlers provided by the language is very exhaustive, but the working principle is same for all of them. Let us first see some of the common HTML events, and then we will see few simple examples to observe them in action. By the end of this chapter, you will find a dedicated exercise for your hands-on event handling practice. These properties are part of the document object as every Node is derived from EventTarget
  • Book cover image for: Start Programming Using HTML, CSS, and JavaScript
    If you use JavaScript in web documents only to augment HTML with behavior, then you get what is usually called Dynamic HTML or DHTML. In such cases, JavaScript should only be used to enhance a visitor’s browsing experience. The actual content that a visitor can read, however, should by no means be dependent on JavaScript. On the other hand, if you go beyond that limitation of merely enhancing a visitor’s experience, you get what is called a web application . The HTML5 specification de-fines a whole lot of objects that allow you to perform application-like feats such as manipulating graphics or storing and retrieving data. Such sets of objects are called application programming interfaces or APIs because programmers use them for inter-acting with di ff erent (software and hardware) components. There’s simply too much of everything, so we’re not going to plunge into details. I’ll just leave you some clues at the end of this course as to which directions you can take. They are gathered in Appendix B of this book. It doesn’t matter whether you’re up to developing dynamic documents or web appli-cations—there’s one API you will constantly work with. It is called the Document Object Model API, or DOM API. Think of DOM as being an object representation of the collection of all the HTML elements and strings of text positioned on a web page. By using DOM API, the programmer can manipulate or query any element or string of text on a web page indirectly by manipulating or querying a corresponding DOM object. The fundamental object of the DOM API is the Document object, which represents whatever is displayed in the browser’s window. The Document object is a property of the Window object and can hence be accessed as a global property under the name 12.4. Scripting Documents 233 document . Maria : Has this got anything to do with the document.write() that we’ve been using? Professor : Indeed it has.
  • Book cover image for: Web Programming
    eBook - PDF

    Web Programming

    Building Internet Applications

    • Chris Bates(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    Nothing happens unless it is initiated by an event outside the script. JavaScript is always reactive rather than proactive, with event triggers coming via the browser. An event is any change that the user makes to the state of the browser. You are used to using a lot of event-driven software, although you may not always recognize it as such. For instance, a word processor simply responds to your actions. Most software you ever use is controlled by you. That is not always true about Web applications. Animations created using Macromedia’s Flash software play when the page is 7.6. Events 231 Event Handler Description blur onBlur The input focus is moved from the object, usually when moving from a field of a form or from the form itself. change onChange The value of a field in a form has been changed by the user entering or deleting data. click onClick The mouse is clicked over an element of a page. dblclick onDblClick A form element or a link is clicked twice in rapid succes- sion. dragdrop onDragDrop A system file is dragged with a mouse and dropped onto the browser. focus onFocus Input focus is given to an element. The reverse of blur. keydown onKeyDown A key is depressed but not released. keypress onKeyPress A key is pressed. keyup onKeyUp A depressed key is released. load onLoad The page is loaded by the browser. mousedown onMouseDown A mouse button is pressed. mousemove onMouseMove The mouse, and hence cursor, is moved. mouseout onMouseOut The mouse pointer moves off an element. mouseover onMouseOver The mouse pointer is moved over an element. mouseup onMouseUp The mouse button is released. move onMove A window is moved, maximized or restored either by the user or by a script. resize onResize A Window is resized by the user or by a script. select onSelect A field on a form is selected by clicking the mouse or tabbing from the keyboard. submit onSubmit A form is submitted (the submit button is clicked).
  • Book cover image for: HTML5 and CSS3, Illustrated Complete
    The most widely used programming language for modern web browsers is JavaScript , which you can use to reference and change data associated with parts of HTML documents. Writing code to accomplish this requires a standardized way of referring to the parts of a web page; this system is known as the Document Object Model (DOM) . You can think of the DOM as a hierarchical arrangement of the content of an HTML document into a tree-like structure, which is known as the DOM tree . FIGURE M-1 shows the code for a simple web page along with its corresponding DOM tree. Each item in the DOM tree—including elements, attributes, and text content—is known as a node . CASE You review the underlying concepts of the DOM in preparation for working with JavaScript. Learning Outcomes • Describe the components of the Document Object Model Note that JavaScript has a different definition of a property than CSS, and CSS properties are not considered properties of JavaScript objects. QUICK TIP TABLE M-1: Commonly used properties property refers to example classValue the value of an element’s class attribute one or more class names, separated by spaces innerHTML the content of an object, including any nested HTML tags; compatible with IE8 the text in a p element src the path and source filename for an element with an src attribute the path and filename for an image textContent the text content of an object, excluding any nested HTML tags; not compatible with IE8 the text in a p element value the current value of a form field or an object property the value of the href property for an a element © 2016 Cengage Learning Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience.
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    ‰ ‰ User events, which occur when the user interacts with elements in the page using a mouse (or other pointing device) or a keyboard, such as placing the mouse over an element, clicking an element, or moving the mouse off an element. Table 10-6 provides a recap of the most common events you are likely to come across. TABLE 10-6: Intrinsic Events EVENT PURPOSE onload Document has finished loading. (If used in a frameset, all frames have finished loading.) onunload Document is unloaded, or removed, from a window or frameset. onclick Button on mouse (or other pointing device) has been clicked over the element. ondblclick Button on mouse (or other pointing device) has been double-clicked over the element. onmousedown Button on mouse (or other pointing device) has been depressed (but not released) over the element. onmouseup Button on mouse (or other pointing device) has been released over the element. onmouseover Cursor on mouse (or other pointing device) has been moved onto the element. onmousemove Cursor on mouse (or other pointing device) has been moved while over the element. onmouseout Cursor on mouse (or other pointing device) has been moved off the element. onkeypress A key is pressed and released. onkeydown A key is held down. continues 364 ❘ CHAPTER 10 LEARNING JAVASCRIPT EVENT PURPOSE onkeyup A key is released. onfocus Element receives focus either by a mouse (or other pointing device) clicking it, tabbing order giving focus to that element, or code giving focus to the element. onblur Element loses focus. onsubmit A form is submitted. onreset A form is reset. onselect User selects some text in a text field. onchange A control loses input focus and its value has been changed since gaining focus. You see examples of these events used throughout this and the jQuery chapters. BUILT-IN OBJECTS You learned about the document object at the beginning of the chapter, and now it is time to see some of the objects that are built into the JavaScript language.
  • Book cover image for: JavaScript All-in-One For Dummies
    • Chris Minnick(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    Inside the window is the docu- ment object, which represents the current HTML page. Inside the document object are element nodes, representing the HTML elements that make up your web page. An event listener usually is applied to a single element, such as a button or a text input. The most common way to select a single element is by using the document. getElementById() method, like this: document.getElementById('submitButton') The value passed to getElementById() is a string that should match the value of the id attribute for an element in your document. Setting addEventListener()’s parameters The first parameter is the name of the event to listen for. Unlike when you use event attributes or event handler properties, this is just the event name, without the on prefix. The types of events that can be applied to a node depend on the node. Hundreds of different events can be detected by a browser, including mouse events, touch events, keyboard events, speech recognition events, window scrolling events, and many others. Table 10-1 shows some of the more common events that can be applied to HTML element nodes. Making Things Happen with Events CHAPTER 10 Making Things Happen with Events 187 The second parameter of addEventListener() is a callback function. Note that this must be either an anonymous function or the name of a function defined outside of the addEventListener() function call. If you add parentheses after the name of the function, the function is invoked and JavaScript attempts to use the result of invoking the function as the event handler when the event occurs. This is usually a mistake, as shown in the following code example: function handleClick(){ alert(`I've been clicked!`); } document.addEventListener('click', handleClick()); TABLE 10-1 Events Supported by All HTML Elements Event . . . . . . Occurs When This Happens abort The loading of a file is aborted. change An element’s value has changed since losing and regaining focus.
  • Book cover image for: Learning jQuery 3 - Fifth Edition
    • Adam Boduch, Jonathan Chaffer, Karl Swedberg(Authors)
    • 2017(Publication Date)
    • Packt Publishing
      (Publisher)

    Handling Events

    JavaScript has several built-in ways of reacting to user interaction and other events. To make a page dynamic and responsive, we need to harness this capability so that we can, at the appropriate times, use the jQuery techniques you learned so far and the other tricks you'll learn later. While we could do this with vanilla JavaScript, jQuery enhances and extends the basic event-handling mechanisms to give them a more elegant syntax while making them more powerful at the same time.
    In this chapter, we will cover:
    • Executing JavaScript code when the page is ready
    • Handling user events, such as mouse clicks and keystrokes
    • The flow of events through the document, and how to manipulate that flow
    • Simulating events as if the user initiated them
    Passage contains an image

    Performing tasks on page load

    We have already seen how to make jQuery react to the loading of a web page. The $(() => {}) event handler can be used to run code that depends on HTML elements, but there's a bit more to be said about it.
    Passage contains an image

    Timing of code execution

    In Chapter 1 , Getting Started , we noted that $(() => {}) was jQuery's primary way to perform tasks on page load. It is not, however, the only method at our disposal. The native window.onload event can do the same thing. While the two methods are similar, it is important to recognize their difference in timing, even though it can be quite subtle depending on the number of resources being loaded.
    The window.onload event fires when a document is completely downloaded to the browser. This means that every element on the page is ready to be manipulated by JavaScript, which is a boon for writing feature-rich code without worrying about load order.
    On the other hand, a handler registered using $(() => {}) is invoked when the DOM is completely ready for use. This also means that all elements are accessible by our scripts, but does not mean that every associated file has been downloaded. As soon as the HTML file has been downloaded and parsed into a DOM tree, the code can run.
  • Book cover image for: Digital Multimedia
    • Nigel Chapman, Jenny Chapman(Authors)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    In the HTML DOM each Element object has properties for each attribute. Most of these properties have the same name as the attribute, but the class attribute is accessed through the className property. Methods of the document object, including getElementById and getElementsByTagName (which returns an array) can be used to retrieve nodes. The methods document.createElement and document.createTextNode can be used to create new nodes, which can be inserted into the tree to add new elements to the page. Many changes to the appearance of a page can be achieved by altering the value of the properties corresponding to attributes of one or more elements. Changing the value of the className property of the body object can change the appearance of the entire page. Scripts are added to XHTML documents using the script element, either to point to an external script file or to embed JavaScript code in the document. The addEventListener method takes two arguments: the name of an event and a function which will act as the listener for events of that type. The listener function receives an Event object as its argument. Add a listener for the load event to the window object to perform any set-up and add listeners to elements within the body of the document. Create controls for changes that are implemented in JavaScript using a script, to ensure that only applicable controls are visible and that users who have disabled scripts will never see the controls. Powerful JavaScript libraries and frameworks are used to create elaborate interactivity with event listeners and DOM objects. KEY POINTS 568 SCRIPTING ActionScript ActionScript is based on ECMAScript 4, a later version of ECMAScript than that which forms the basis of JavaScript. The main difference from the subset of JavaScript which we used in the preceding section is that ActionScript requires all variables to be declared, together with the type of value they may hold.
  • Book cover image for: Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    These events are deprecated, and support is gradually being phased out. This feature is replaced by Mutation Observers, which is covered in The Document Object Model chapter.

    HTML5 Events

    The DOM specification doesn't cover all events that are supported by all browsers. Many browsers have implemented custom events for various purposes based on either user need or a specific use case. HTML5 has an exhaustive list of all events that should be supported by browsers. This section discusses several events in HTML5 that are well supported by browsers. Note that this is not an exhaustive list of all events the browser supports. (Other events will be discussed throughout this book.)
    The contextmenu Event
    Windows 95 introduced the concept of context menus to PC users via a right mouse click. Soon, that paradigm was being mimicked on the Web. The problem developers were facing was how to detect that a context menu should be displayed (in Windows, it's a right click; on a Mac, it's a Ctrl+click) and then how to avoid the default context menu for the action. This resulted in the introduction of the contextmenu event to specifically indicate when a context menu is about to be displayed, allowing developers to cancel the default context menu and provide their own.
    The contextmenu event bubbles, so a single event handler can be assigned to a document that handles all such events for the page. The target of the event is the element that was acted on. This event can be canceled in all browsers, using event.preventDefault() in DOM-compliant browsers and setting event.returnValue to false in Internet Explorer 8 and earlier. The contextmenu event is considered a mouse event and so has all of the properties related to the cursor position. Typically, a custom context menu is displayed using an oncontextmenu event handler and hidden again using the onclick
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.