Event types. Events in javaScript Dom events javascript

💖 Do you like it? Share the link with your friends

In this lesson we will look at the main types of events that you can intercept with using JavaScript to execute some code.

Event categories

All JavaScript events can be divided into the following categories: Mouse Events, Keyboard Events, Frame/Object Events, Form Events, Drag Events , Animation Events, Clipboard Events, Media Events, Transition Events, Server-Sent Events, Touch Events, Print Events (Print Events), miscellaneous events (Misc Events).

Attention: all events in JavaScript are written in lowercase (small) letters.

Mouse events
  • mousedown - event occurs when the mouse button is pressed over some element, but has not yet been released.
  • mouseup - the event occurs when the mouse button over some element has passed from the pressed state to the released state.
  • click - the event occurs when the user clicks the mouse on the element. The order in which click events occur (for the left and middle mouse buttons) is mousedown -> mouseup -> click .
  • contextmenu - the event occurs when the user right-clicks on an element. The order of events associated with the contextmenu (for the right mouse button) is mousedown -> mouseup -> contextmenu .
  • dblclick - event occurs when the user double-clicks an element. The order of occurrence of events associated with dblclick is: mousedown -> mouseup -> click -> mousedown -> mouseup -> click -> dblclick .
  • mouseover - the event occurs when the mouse cursor enters an area owned by an element or one of its children.
  • mouseout - event occurs when the mouse cursor moves out of an area owned by an element or one of its children.
  • mousemove - event occurs when the mouse cursor moves inside the area belonging to the element.
  • mouseenter - event occurs when the mouse pointer enters an area owned by an element. This event is often used in conjunction with the mouseleave event, which occurs when the mouse pointer leaves the area owned by an element. The mouseenter event is similar to the mouseover event and differs only in that the mouseenter event does not bubble (we will get to know the concept of event bubbling a little later).
  • mouseleave - event occurs when the mouse pointer leaves the area owned by the element. The mouseleave event is similar to the mouseout event and differs only in that the mouseleave event does not bubble (we will get to know the concept of event bubbles a little later).
Keyboard events

The order of occurrence of events is: keydown -> keypress -> keyup .

  • keydown - the event occurs when a key on the keyboard above an element is pressed but not yet released.
  • keyup - the event occurs when a pressed key on the keyboard above an element changes to the released state.
  • keypress - event occurs when the user presses a key on the keyboard above an element.
Object and Frame Events
  • beforeunload - the event occurs before the document is unloaded. This event allows you to display an additional message in the confirmation dialog, "Are you sure you want to leave this page?" The standard message that appears when closing a document may differ depending on the different browsers. But you cannot change or delete it, you can only use this method to add your own message to it, which will be displayed along with the default message.
  • error - the event is triggered when an error occurs, which occurs when loading an external file (for example, a document or image).
  • hashchange - the event occurs when the anchor part (starts with the "#" symbol) of the current URL changes.
  • load - event occurs when loading of an object is completed. The load event is most often used on the body element to execute a script immediately after the web page has fully loaded.
  • unload - the event occurs when a page is unloaded (for example, when a browser tab (window) is closed).
  • pageshow - event occurs when the user navigates to a web page, i.e. after the page becomes available to the user. The pageshow event is similar to the load event, except that it fires every time the page is loaded, even if it is loaded from the cache. When a page is first loaded, the pageshow event fires immediately after the load event.
  • pagehide - the event occurs when the user leaves the page (the pagehide event occurs before the unload event). In addition, this event, unlike the unload event, does not prevent page caching.
  • resize - event occurs when the browser window is resized.
  • scroll - The event occurs when you scroll the content of an element that has a scrollbar.
Form and Control Events
  • focus - the event occurs when the element receives focus. This event does not pop up.
  • blur - event occurs when an object loses focus. This event does not pop up.
  • focusin - event occurs when the element receives focus. The focusin event is similar to the focus event, but differs from it in that it bubbles. Therefore, it can be used when you need to find out who is losing focus: the element or its child?
  • focusout - event occurs when an element is about to lose focus. The focusout event is similar to the blur event, but differs from it in that it bubbles. Therefore, it can be used when you need to find out who is losing focus: the element or its child?
  • change - the event occurs when the element's value changes, but after the element has lost focus. In addition to the change event in JavaScript, there is also a similar input event, which differs from the change event in that it occurs immediately after the element's value changes. The change event, unlike the input event, also works with keygen and select elements. For radiobuttons and checkboxes, the change event occurs when the state of these elements changes.
  • input - the event occurs after the value of the input element or textarea element changes.
  • invalid - The event occurs when an input element whose data needs to be sent along with other form data to the server contains invalid data.
  • reset - the event occurs before the form is cleared, which is done by an input element with type="reset" .
  • search - The event occurs after the user presses the Enter key or clicks the " x " (cancel) button on an input element with type="search" .
  • select - the event occurs after you have selected some text in the element. select event Mainly used for input element with type="text" or textarea .
  • submit - the event occurs before the form is submitted to the server.
Drag Events

Events associated with the dragged object (draggable target, source object):

  • dragstart – the event occurs when the user starts dragging an element;
  • drag – event occurs when the user drags an element;
  • dragend – the event occurs when the user has finished dragging the element, i.e. when I released the mouse cursor.

Events associated with the drop target that receives the draggable target:

  • dragenter – the event occurs when a draggable target has entered the area of ​​a drop target that can accept a draggable target.
  • ragleave - the event occurs when a dragged object (draggable target) leaves the boundaries of the element (drop target) that can accept it.
  • dragover - the event occurs when a draggable target moves into the area of ​​an element (drop target) that can accept it.
  • drop - the event occurs when the user releases a draggable object into the area of ​​an element (drop target) that can accept it.
Animation Events

Three events that can happen while a CSS animation is running:

  • animationstart - Occurs when the CSS animation has started.
  • animationiteration - Occurs when a CSS animation is executed repeatedly.
  • animationend - occurs when CSS animation ended.
Clipboard events
  • copy - event occurs when the user copies the contents of an element. The copy event also occurs when the user copies an element (for example, images created with the img element). The copy event is used primarily for input elements with type="text" .
  • cut - event occurs when the user cuts the content of an element.
  • paste - the event occurs when the user pastes some content into an element.
Print Events
  • afterprint - The event occurs when the page begins to print (that is, after clicking the Print button in the dialog box) or if the Print dialog box has been closed.
  • beforeprint - the event occurs before the page is printed, i.e. before opening the Print dialog box.
Transition Events
  • transitionend - the event fires when the CSS transition is complete. Note: If a transition is removed before completion (for example, if CSS property transition-property has been removed), then the transitionend event will not fire.
Events sent by the server
  • error - the event occurs when an error occurs with the event source. The error usually occurs when communication is broken. If this happens, the EventSource object will automatically try to connect to the server.
  • open - the event occurs when the connection to the event source is open.
  • message - the event occurs when a message is received through the event source.
    The message event object supports the following properties:
    • data - contains the message.
    • origin - URL of the document that triggered the event.
    • lastEventId - identifier (id) of the last received message.
Media Events

During the audio/video loading process, events occur in the following order: loadstart -> durationchange -> loadedmetadata -> loadeddata -> progress -> canplay -> canplaythrough .

  • abort - event occurs when audio/video loading is interrupted. This event occurs when the download of media data was interrupted (cancelled), and not because an error occurred.
  • error - event occurs when an error occurs while loading audio/video.
  • stalled - the event occurs when the browser tries to receive media data, but the data is not available.
  • - the event occurs when the browser starts searching for the specified audio/video, i.e. when the download process begins.
  • durationchange - event occurs when the duration of the audio/video changes. If audio/video is loaded, the duration will vary from "NaN" to the actual duration of the audio/video.
  • loadedmetadata - event fired when metadata for the specified audio/video has been loaded. Audio/video metadata consists of: duration, size (video only) and text track.
  • loadeddata - the event occurs after the first frame of media has loaded.
  • progress - event occurs when the browser downloads the specified audio/video.
  • canplay - the event occurs when the browser can start playing the specified audio/video (that is, when the audio/video stream is buffered enough for the browser to start playing it).
  • canplaythrough - the event occurs at the point in time when the browser can play the specified media without stopping for buffering.
  • ended - the event occurs when audio/video playback has completed (reached the end). This event can be used to display messages like “Thank you for your attention”, “Thank you for watching”, etc.
  • pause - event occurs when audio/video playback is paused by the user or by code (programmatically).
  • play - event occurs when audio/video playback starts. It also occurs when the audio/video has been unpaused and begins to play.
  • playing - The event occurs when audio/video is playing after it has been paused or stopped for buffering.
  • ratechange - event occurs when the audio/video playback speed changes.
  • seeking - the event occurs when the user begins to move the slider (transition) to a new time position of the audio/video being played.
  • sought - the event occurs when the user has finished moving the slider (transition) to a new temporary position of the audio/video being played. The sought event is the opposite of the seeking event. To get the current playback position, use the currentTime property of the Audio / Video object.
  • timeupdate - the event occurs when the time position of the audio/video being played changes.
    This event occurs:
    • when playing an audio/video stream.
    • when moving the slider to a new time position of the audio/video being played.
    The timeupdate event is often used in conjunction with the Audio/Video object's currentTime property, which returns the current time position of the currently playing audio/video in seconds.
  • volumechange – the event occurs every time the volume of the playing video/audio stream changes.
    This event occurs when:
    • increasing or decreasing the volume;
    • muting or unmuting the sound.
  • waiting - the event occurs when the video is stopped for buffering.
Various events
  • toggle - The event occurs when the user opens or closes the details element. The details element is intended to create additional information, which the user can view or hide if necessary.
  • wheel - the event occurs when the mouse wheel scrolls forward or backward over an element.
Tasks
  • Is the "Keypress on keyboard (onkeypress)" event complex? And if it is, then as a result of what simple events does it arise?
  • For example, you have 2 p elements and the user moves the mouse from an area belonging to one p element to an area belonging to another p element. What events occur in this case, and what elements generate them?
  • While working with the page, the user performs various actions: clicks mouse buttons, enters text on the keyboard. Each such action is a browser event. It can be monitored and specific lines of the program executed when they occur. JavaScript has event handlers for this. In addition to user actions, there are other browser events, such as the page being fully loaded.

    Each event has its own name. click is a press of the left mouse button, keydown is a key press, focus is the appearance of a form element in focus, Event handling

    The function that is executed when an event fires is called an event handler. Each type of event has its own handler. The name of the handler consists of the word on and the name of the event. For example, the click event handler is called onclick. Events do not occur on the page in general, but on a specific element. Accordingly, the handler is not separate function. The handler is placed on some element of the page.

    There are different ways to assign an event handler to an element. You can assign a handler via a tag attribute. The code that should be executed when the event fires is written in the attribute value. Let's create a page, add a button to it and assign a click event handler to it:

    1
    2
    3
    4
    5
    6
    7

    Page

    JavaScript:

    JavaScript:

    17
    18
    19
    20
    21
    22

    var inform = function () ( alert("Another button"); ); var mbutton = document.getElementById("mbutton"); mbutton.onclick = inform;

    When a function is assigned to a handler, there are no parentheses after the function name. If you put parentheses, then this will not be an assignment to a function, but a call to execution.

    There is a method addEventListener() which also assigns an event handler to the element. It is considered more modern. It's not used often these days, but there are new events in JavaScript that can only be handled using this method.

    element.addEventListener(event, function)

    Options:

    event - the event that needs to be processed

    function - a function that becomes a handler

    In parameters this method The name of the event is written in quotes and the word on does not need to be written before it.

    HTML code:

    New button

    JavaScript:

    24
    25
    26
    27
    28
    29

    var newinform = function () ( alert("New button pressed"); ); var newbutton = document.getElementById("newbutton"); newbutton.addEventListener("click", newinform);

    The removeEventListener() method allows you to remove a handler.

    element.removeEventListener(event, function)

    Using the method discussed above, you can assign several handlers for one event to an element. Then you need to delete each of them separately.

    Event object

    Each time an event is fired, an event object is generated. The object contains information about the event. Different event types have different objects. But there are also properties that any object has. For example, the type property contains the event type.

    The event object is passed as a parameter to the function, which is the handler. To access an object, you need to create a parameter in the function. The object is accessed through this parameter. If a function expects other parameters, then the event object must be the first parameter. Let's change the handler for the button whose id is equal to "button". Let's get access to the event object. Instead of a message about a button press, we will display the event type. Now the handler will look like this:

    13
    14
    15
    16

    button.onclick = function (event) ( alert(event.type); );

    Click on the button, the type of event that was triggered will be displayed.

    All event objects have a currentTarget property. It returns the element on which the event was triggered. This may seem pointless. After all, the handler is assigned to a specific element. Why return this element again? But with browser events, everything is somewhat more complicated. A little later you will learn how it is used. We will consider other properties when studying specific events.

    From the author: after the web page is loaded and completely ready, a whole cascade of events is launched in JavaScript, which increases even more when the user begins to interact with the page in one way or another. Events can include loading a page, scrolling it, clicking a button, or even filling out a form. To trigger events in JavaScript, you need special code that you design and write yourself, thereby building deeper interaction.

    Events in JS can be divided into 4 large groups:

    UI events: Fired when the user interacts with the browser UI (the buttons around the web page that are part of the browser interface). Such events also include those actions that the page performs independently of the user. These events include window resizing, page scrolling, and loading and unloading content.

    Keyboard, Mouse, and Touchscreen Events: Triggered when the user presses or releases keys on the keyboard, controls the mouse, controls the trackpad, or operates the touchscreen.

    Focus and handicap events. Mostly associated with forms: the input field "gets focus" when the user is ready to interact with it. Other events track form submissions, changes in form field values, etc.

    JavaScript. Fast start

    Mutation events and observers. Mutating elements are tracked when the DOM structure changes: for example, when elements on a page are inserted or removed using a script.

    Event Handler Binding

    A special code that will only work for specific element DOM, creates an event handler. There are three ways to create an event handler in JS:

    1. Standard HTML event handler via attributes

    The oldest method of event binding, one of the most common to this day. The method uses special attributes in the markup. Eg:

    < input type = "text" id = "username" onblur = "checkName()" >

    In the example above, after a field receives focus and the user moves on to fill out the next field (for example, using TAB or a regular click), the element will call the checkName function, which is written in JS.
    Standard HTML event handlers are not recommended for use in modern development, mainly due to the fact that the functionality is mixed with markup, which complicates the work and debugging of the code.

    2. Standard event handlers in the DOM

    This technique separates JS and markup, but has the same limitation - events can only be assigned one function. The equivalent HTML event handler entry in the DOM would be:

    var username = document.getElementbyId("username"); username.onblur = checkName;

    username. onblur = checkName ;

    JavaScript. Fast start

    Explore JavaScript basics on a practical example of creating a web application

    As in the previous example, the checkName function runs after the form element loses focus.

    3. Event Listeners

    A modern method of adding an event handler that allows you to chain multiple events and functions:

    var username = document.getElementbyId("username"); username.addEventListener("blur", checkName, false);

    var username = document. getElementbyId("username");

    username. addEventListener ("blur" , checkName , false ) ;

    The boolean value at the end indicates whether the event should be captured. Typically set to false. In simple scripts, an event is often written as an anonymous function:

    var username = document.getElementbyId("username"); username.addEventListener("blur", function() ( // actions to trigger the event ))

    Not all events are equal

    It is important to understand that not all events can be treated the same. The scroll and resize events are fired very often, which is why you need to work with them very carefully so as not to reduce the speed of the script. The same applies to seemingly harmless events such as input. The script's performance may suffer greatly if it tries to constantly respond to the frequently triggered input event on the range slider.

    Not all events are tracked

    Observers of mutations on this moment cannot track all changes to all elements on a page. For example, there is no way to track changes in the height of an element (when a container in responsive design narrows, the text inside it is rearranged and the elements become longer). Still, there are ways to track changes, I will talk about this in the next article.

    Attach events to the right elements

    The onclick event applies to many elements, including links. Eat general rule– It is not recommended to attach JS code to links. By clicking on the link, the user should be taken to another area of ​​the site or to an anchor. If you need a UI element with which you can change something on the same page, then a button is suitable for you. You can easily add JavaScript to the button.

    Don't use JavaScript if you can do it with CSS help

    Compared to CSS, JavaScript is slow and unreliable. Essentially, CSS should be used as an alternative to complex scripts wherever possible. However, CSS doesn't do everything. It does a good job with :hover (in many cases it replaces touch events) and can also replace click event using:target in some cases. CSS animation automatically starts after the page loads, and there are also special CSS states that can be triggered for elements such as radio buttons. However, anything more complex is usually best left to JavaScript.

    If you haven't noticed, most apps and websites are pretty boring when they stand on their own. They greet you with a pompous and flashy interface, but the impression of it quickly fades away if you don’t start interacting with them:

    The reason for this is very simple. Apps exist to respond to your actions. There are some incentives that force you to launch the applications and start using them. Everything else they do after that depends largely on what you tell them to do. This is where things get really interesting.

    You tell applications what they need to do by making them react to something known called an event. In this article, we'll take an overview of what events are and how they can be used.

    What are events?

    In general, everything you create can be modeled by the following statement:

    There are countless things you can do to fill in the gaps in this statement. The first space tells you that something is happening. The second space describes the reaction to this. Here are some examples of filling out this application:

    This universal model applies to all the codes that we have compiled. This model also applies to all the code that every developer/designer you know has ever written for their applications.

    There's no way around this model, so... there's no point in trying. Instead, you need to look deeper into this very useful thing known as an event.

    An event is nothing more than a signal. He reports that something just happened. This something could be a mouse click. This could be a key press on the keyboard. This could be changing the size of your window. It could simply be that your document has just been downloaded.

    You must understand that this signal can be built in by hundreds different ways in JavaScript... or in something custom that you created just for your application in a single instance.

    Let's return to our model. The events make up the first half of the statement:

    Events determine the thing that happens. They are sending a signal. The second part of the model determines the reaction to the event:

    After all, what good is a signal if there is no one on the other side waiting for it and then taking action accordingly?! Okay - now that you have a fair understanding of what events are, let's take a look at how events live in the preserve known as JavaScript.

    Events and JavaScript

    Given the importance of events, it is not surprising that JavaScript provides numerous tools for working with them. There are two main things you need to do to work with events:

    • Event tracking;
    • Reaction to events.

    These two steps seem pretty simple, but don't forget that we're dealing with JavaScript. Simplicity is just a smokescreen that can hide serious problems that you will get if you take the wrong actions. Perhaps I'm being too dramatic? Well, let's figure it out together.

    1. Event tracking

    To be honest, at one time I went through everything you do inside an application to detect events. Sometimes, your application detects the event automatically, such as when loading. Sometimes an event is defined as the result of your interaction with an application.

    It should be noted that the application is bombarded with events constantly, regardless of whether you need to capture them or not. Our task is to tell the application to track only those events that we need.

    The hard work of tracking down the events we need is done by a function called addEventListener. This function is responsible for constantly being alert and notifying other parts of your application when some interesting event occurs.

    The way you use this function looks like this:

    source.addEventListener(eventName, eventHandler, false);

    Let's analyze what each part of this function means.

    Source

    You call addEventListener on the element or object on which you want to listen for events. Typically this is a DOM element, but it can also be a document, window, or any other object that can generate events.

    Event name

    The first argument you provide to the addEventListener function is the name of the event you want to listen for. Full list The events you can interact with are too numerous to list here in full (check out this page), but some of the most common events you'll encounter are as follows:

    Event The event is happening...
    click ...when you press and release the primary button of your mouse/trackpad/etc.
    mousemove ...when the mouse cursor moves.
    mouseover ...when you hover your mouse over an element. This event is typically used when selecting objects!
    mouseout ...when the mouse cursor leaves the element area.
    dblclick ...when you double-click the mouse.
    DOMContentLoaded ...when your element's DOM is fully loaded.
    load ...when your entire document (DOM, additional elements: images, scripts, etc.) is fully loaded.
    keydown ...when you press a key on your keyboard.
    keyup ... when you release a key on the keyboard.
    scroll ...when you scroll an element.
    wheel &
    DOMMouseScroll
    ...every time you use the mouse wheel to scroll up or down.

    In subsequent articles we will look at many of these events in more detail. For now, just pay attention to the click event, since we'll use it later.

    Event Handler

    As the second argument, you must specify a function that will be called when the event is captured. This function is called an event handler. Below I will tell you about it in detail.

    To capture or not to capture, that is the question!

    The last argument can be true or false.

    Let's summarize all of the above

    Now that you're familiar with the addEventListener function, let's summarize everything with one real-world example:

    document.addEventListener("click", changeColor, false);

    In this example, our addEventListener function is attached to a document object. When a click event is detected, it calls the changeColor function (also known as an event handler) in response to that event. This brings us close to the concept of reaction to events, which we will discuss in the next section.

    2. Reaction to events

    As described in the previous section, event tracking (listening) is handled by the addEventListener function. Once an event is captured, it must be handled by an event handler. I wasn't kidding when I mentioned earlier that an event handler is nothing more than a function:

    function normalAndBoring() ( // I really like all the different things that can be inside this function! )

    The only difference between a standard function and one specified as an event handler is that the event handler is specifically called by name in the addEventListener call:

    document.addEventListener("click", changeColor, false); function changeColor() ( // I'm important!!! )

    Any code you place inside an event handler will be executed when the addEventListenerfunction catches the event you want. It's pretty simple!

    Simple example

    The best way to understand what we just learned is to see it in fully working code. To get us moving in parallel, add the following markup and code to your HTML document:

    Click Anywhere! document.addEventListener("click", changeColor, false); function changeColor() ( document.body.style.backgroundColor = "#FFC926"; )

    Initially, if you view the document in a browser, you will just see a blank page:

    However, everything changes if you click anywhere on the page. Once you do this, the background color of your page will change from white to bright yellow.

    The reason for this is quite easy to understand. Let's look at the code:

    The addEventListener call is identical to what we've already covered, so let's skip that step. Instead, look at the changeColor event handler:

    document.addEventListener("click", changeColor, false); function changeColor() ( document.body.style.backgroundColor = "#FFC926"; )

    This function is called when a click event is detected on the document. When this function is called, it sets the background color of the body element to bright yellow. Relating this to the statement we looked at at the very beginning, we will see that this example would look like this:

    If you understand the essence of what is happening, then that's great! You've just learned about one of the most important concepts you'll encounter in programming. But we're not done yet. We won't let event handlers off the hook that easily, so let's look at one more thing.

    Event Arguments and Event Type

    The event handler does more than just get called when an event is captured through the event tracking function. It also provides access to the main event object through its arguments. To easily access this event object, we must change the handler signature to support these arguments.

    function myEventHandler(e) ( // event handler elements )

    For now, the event handler is still a good old function. But that's what we need, a function that takes one argument... an event argument!

    You can use any valid identifier for the argument, but I generally prefer e because that's what all the cool kids do. There is nothing technically wrong with defining an event as follows.

    The topic of the events is very important and very interesting. Thanks to it, you can do a lot of interesting things that the user will be delighted with. An event in JavaScript is a specific action that is triggered either by the user or the browser. For example, an event could be a mouse click on a button, mouse movement, focusing on an element, changing a value in a text field, resizing a browser window, and so on.

    I have prepared a table with all the events (that I know at least) in JavaScript. In it you will find, firstly, the name of the event, elements that can generate this event and a description of the JavaScript event itself.

    EventAn objectCause of occurrence
    AbortionImageInterrupting image loading
    BlurLost element focus
    ChangeFileUpload, Select, Text, TextareaChange value
    ClickArea, Button, Checkbox, Document, Link, Radio, Reset, SubmitMouse click on an element
    DblClickArea, Document, LinkDouble click on an element
    DragDropWindowMove to browser window
    FocusButton, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, WindowSetting focus on an element
    KeyDownPressing a key on the keyboard
    KeyPressDocument, Image, Link, TextareaHolding a key on the keyboard
    KeyUpDocument, Image, Link, TextareaReleasing a key on the keyboard
    LoadDocument, Image, Layer, Window
    MouseDownButton, Document, LinkMouse button pressed
    MouseMoveWindowMouse in motion
    MouseOutArea, Layer, LinkThe mouse goes beyond the borders of the element
    MouseOverArea, Layer, LinkThe mouse is over the element
    MouseUpButton, Document, LinkMouse button released
    MoveFrameMoving an element
    ResetFormReset form
    ResizeFrame, WindowResizing
    SelectText, TextareaText selection
    SubmitFormData transfer
    UnloadWindowUnloading the current page

    Now let's figure out how to use events in JavaScript. There are so-called event handlers. Event handlers determine what will happen when a certain event occurs. Event handlers in JavaScript have the following general form:

    OnEventName

    That is, first comes the prefix “on”, and then the name of the event, for example, the following event handlers: onFocus, onClick, onSubmit, and so on. I think there are no questions here. And now the main question: “How to use events in JavaScript?”. The scope of their application is huge, and now we will look at one problem. There are three links on the page. Each of the links is responsible for a different background color (for example, white, yellow and green). At first the background is white. When you hover your mouse over a specific link, the background color changes. When you move the mouse away, the background color returns to the default color. When you click on a link, the background color is retained as the default.




    a (
    color:blue;
    text-decoration: underline;
    cursor: pointer;
    }


    var default_color = "white";

    function setTempColor(color) (
    document.bgColor = color;
    }

    function setDefaultColor(color) (
    default_color = color;
    }

    function defaultColor() (
    document.bgColor = default_color;
    }



    White
    Yellow
    Green

    Let's look at this script, or rather an entire HTML page with JavaScript and CSS support (in other words, this is an example of DHTML). First come the usual HTML tags, with which any HTML page begins. Next, we create a style in which we require that all links on a given page be blue, underlined, and that the mouse pointer on them be in the form of a "Pointer". You may say: “Why do you need to set a style? After all, the links will be exactly the same.” That’s right, links, but we don’t have links as such (after all, there is no href attribute in the tag), so they will be simple black text by default (however, you can also click on the text). Therefore, style is a must. You can remove it and see what happens. Better yet, add the href attribute (with any value, even empty) and explain why the script stopped working. Then JavaScript begins. We create a variable default_color responsible for the default color. Next come three functions:

    The setTempColor() function is responsible for temporarily changing the color.

    The setDefaultColor() function is responsible for changing the default color.

    The defaultColor() function sets the default background color.

    Then there are links with attributes in the form of event handlers. When you hover the mouse over a link, the MouseOver event occurs; accordingly, the onMouseOver event handler calls the setTempColor() function and passes the corresponding parameter. When you remove the mouse from an element, the MouseOut event is raised, and then the defaultColor() function is called, which sets the background color to the default color. And finally, when the mouse clicks on the link (onClick handler), the setDefaultColor() function is called, which sets the color specified in the parameter to the default background color. As you can see, everything is quite simple.

    This was the principle of using events in JavaScript, and then everything depends only on your imagination!



    tell friends