js click events. Sequence of script execution. JavaScript onclick event and three ways to handle events

Event Handling

Client programs for JavaScript are based on a programming model where program execution is event-driven. With this style of programming, the web browser generates an event when something happens to the document or some element of it. For example, a web browser generates an event when it finishes loading a document when the user hovers the mouse over a hyperlink or presses a key on the keyboard.

If a JavaScript application is interested in a specific event type for specific element document, it can register one or more functions that will be called when this event occurs. Please be aware that this is not unique feature web programming: all applications with graphical interface Users act this way - they constantly wait for something to happen (i.e., wait for events to appear) and respond to what happens.

The event type is a string that identifies the type of action that caused the event. The type "mousemove", for example, means that the user has moved the mouse pointer. The type "keydown" means that a key on the keyboard was pressed. And the “load” type means that the download of the document (or some other resource) from the network has completed. Because the event type is just a string, it is sometimes called the event name.

The target of an event is the object in which the event occurred or with which the event is associated. When talking about an event, they usually mention the type and purpose of the event. For example, the "load" event of a Window object or the "click" event of a . The most typical goals of events in client applications in JavaScript are Window, Document, and Element objects, but some types of events can occur in other object types.

An event handler is a function that processes, or responds to, an event. Applications must register their event handler functions with the web browser, specifying the event type and purpose. When an event of the specified type occurs on the specified target, the browser will invoke the handler. When event handlers are called on an object, we sometimes say that the browser has "raised" or "thrown" the event.

An event object is an object associated with a specific event and containing information about that event. Event objects are passed to the event handler function as an argument (except IE8 and newer earlier versions, where the event object is only available as a global event variable). All event objects have the property type, which defines the event type, and the property target, defining the purpose of the event.

For each event type, a set of properties is defined in the associated event object. For example, an object associated with mouse events includes the coordinates of the mouse pointer, and an object associated with keyboard events contains information about the key pressed and the modifier keys pressed. For many event types, only standard properties such as type and target are defined and no additional properties are passed. useful information. For these types of events, the mere occurrence of the event is important and no other information is relevant.

Event propagation is the process by which the browser decides which objects to call event handlers on. In the event of events intended for the only object(such as the “load” event of the Window object), there is no need to propagate them. However, when an event occurs on a document element, it propagates, or "bubbles," up the document tree.

If the user clicks on a hyperlink, the "mousemove" event will first be raised on the element , defining this link. It will then be delivered to the containing elements: perhaps the element

The element and the Document object itself. Sometimes it is more convenient to register a single event handler on a Document object or other container element than to register on all the elements of interest.

Having defined some terms, we can move on to exploring issues related to events and their processing.

Registering Event Handlers

There are two main ways to register event handlers. The first, which appeared early in the development of the World Wide Web, is to set the property of the object or document element that is the target of the event. The second method, newer and more universal, is to pass a handler to a method of an object or element.

The matter is complicated by the fact that each technique has two versions. You can set an event handler property in JavaScript code or in a document element by defining the corresponding attribute directly in the HTML markup. Registering handlers with a method call can be done by a standard method called addEventListener(), which is supported by all browsers except IE versions 8 and below, and another method called attachEvent(), supported by all versions of IE up to IE9.

Setting event handler properties

The simplest way to register an event handler is to set a property of the event target to the desired handler function. By convention, event handler properties have names consisting of the word "on" followed by the event name: onclick, onchange, onload, onmouseover, etc. Note that these property names are case-sensitive and use only lowercase characters, even when the event type name is multiple words (for example, "readystatechange"). Below are two examples of registering event handlers:

// Assign the function to the onload property of the Window object. // The function is an event handler: it is called when the document is loaded window.onload = function() ( // Find the element var elt = document.getElementById("shipping_address"); // Register an event handler that will be called // directly before submitting the form elt.onsubmit = function() ( return validate(this); ) )

This method of registering event handlers is supported in all browsers for all commonly used event types. In general, all widely supported application interfaces that define their events allow handlers to be registered by setting the properties of the event handlers.

The disadvantage of using event handler properties is that they are designed with the assumption that event targets will have at most one handler per event type. When creating a library for use in arbitrary documents, it is better to use a technique (such as calling the addEventListener() method) to register handlers that does not change or overwrite previously registered handlers.

Setting event handler attributes

The properties of event handlers on document elements can also be set by defining attribute values ​​in the corresponding HTML tags. In this case, the attribute value must be a string of JavaScript code. This program code should not be a complete declaration of the event handler function, but only its body. That is, the implementation of the event handler in HTML markup should not be enclosed in curly braces and preceded by the function keyword. For example:

If the value of an event handler HTML attribute consists of multiple JavaScript statements, they must be separated by semicolons, or the attribute value must appear on multiple lines.

Some event types are intended for the browser as a whole, rather than for any specific document element. Handlers for such events in JavaScript are registered in the Window object. In HTML markup they must be placed in a tag, but the browser will register them in the Window object. The following is a complete list of such event handlers defined by the draft HTML5 specification:

onafterprint onfocus ononline onresize onbeforeprint onhashchange onpagehide onstorage onbeforeunload onload onpageshow onundo onblur onmessage onpopstate onunload onerror onoffline onredo

When developing client-side scripts, it is common practice to separate the HTML markup from the JavaScript code. Programmers who follow this rule avoid (or at least try to avoid) using HTML event handler attributes to avoid mixing JavaScript code with HTML markup.

addEventListener()

In the standard event model, supported by all browsers except IE versions 8 and below, the target of an event can be any object - including Window and Document objects and all Elements objects of document elements - defining a method called addEventListener() with which event handlers can be registered for this purpose.

The addEventListener() method takes three arguments. The first is the event type for which the handler is registered. The event type (or name) must be a string and must not include the "on" prefix used when setting the properties of event handlers. The second argument to the addEventListener() method is a function that should be called when an event of the specified type occurs. The last argument is passed to the addEventListener() method with a boolean value. Typically this argument is false. If you pass it true, the function will be registered as an interception handler and will be called in another phase of event propagation.

The specification may eventually change so that it is acceptable to omit the third argument rather than explicitly passing it false, but as of this writing, the omission of the third argument results in an error in some current browsers.

The following snippet registers two "click" event handlers on the element. Note the differences between the two techniques used:

Click me! var b = document.getElementById("mybutton"); b.onclick = function() ( alert("Thanks for clicking on me!"); ); b.addEventListener("click", function() (alert("Thanks again!")), false);

Calling the addEventListener() method with the string "click" as the first argument does not affect the value of the onclick property. In the snippet above, clicking the button will bring up two alert() dialog boxes. But more importantly, the addEventListener() method can be called multiple times and can be used to register multiple handler functions for the same event type in the same object. When an event occurs on an object, all handlers registered for that event type will be called, in the order in which they were registered.

Calling the addEventListener() method multiple times on the same object with the same arguments has no effect - the handler function is registered only once and repeated calls do not affect the order in which the handlers are called.

Paired with the addEventListener() method is the removeEventListener() method, which takes the same three arguments, but instead of adding, it removes a handler function from the object. This is often useful when you need to register a temporary event handler and then remove it at some point.

Internet Explorer versions earlier than IE9 do not support the addEventListener() and removeEventListener() methods. IE5 and later define similar methods, attachEvent() and detachEvent() . Because the IE event model does not support an interception phase, the attachEvent() and detachEvent() methods take only two arguments: the event type and the handler function, with the first argument passing the handler property name prefixed with “on” to the methods in IE rather than the type events without this prefix.

Calling event handlers

Once you register an event handler, the web browser will call it automatically when an event of the specified type occurs on the specified object. This section details the order in which event handlers are called, the arguments to the handlers, the context of the call (the value of this), and the purpose of the handler's return value. Unfortunately, some of these details differ between IE versions 8 and below and other browsers.

Event Handler Argument

When an event handler is invoked, it is usually (with one exception, discussed below) passed the event object as a single argument. The properties of an event object contain additional information about the event. The type property, for example, determines the type of event that occurred.

In IE version 8 and below, event handlers registered by setting a property are not passed an event object when called. Instead, the event object is stored in the global variable window.event. For portability, event handlers can be styled as follows so that they use the window.event variable when called without an argument:

The event object is passed to event handlers registered with the attachEvent() method, but they can also use the window.event variable.

When you register an event handler using an HTML attribute, the browser converts a string of JavaScript code into a function. Browsers other than IE create a function with a single argument, event. IE creates a function that takes no arguments. If you use the event identifier in such functions, it will refer to window.event. In either case, event handlers defined in HTML markup can reference an event object using the event identifier.

Event Handler Context

When an event handler is registered by setting a property, it looks like defining a new document element method:

E.onclick = function() ( /* handler implementation */ );

It is therefore not surprising that event handlers are invoked (with one exception regarding IE, which is described below) as methods of the objects in which they are defined. That is, in the body of the event handler, the this keyword refers to the target of the event.

In handlers, the this keyword refers to the target object, even when they were registered using the addEventListener() method. However, unfortunately, this is not the case for the attachEvent() method: handlers registered with the attachEvent() method are called as functions, and in them the this keyword refers to the global (Window) object. This problem can be solved in the following way:

/* Registers the specified function as an event handler of the specified type in the specified object. Ensures that the handler will always be called as a method on the target object. */ function addEvent(target, type, handler) ( if (target.addEventListener) target.addEventListener(type, handler, false); else target.attachEvent("on" + type, function(event) ( // Call the handler as target method, // and pass it the event object return handler.call(target, event ));

Note that event handlers registered in this manner cannot be removed because the reference to the wrapper function passed to the attachEvent() method is not stored anywhere so that it can be passed to the detachEvent() method.

Handler return values

The value returned by an event handler registered by setting an object property or by an HTML attribute should be taken into account. Typically, returning false tells the browser that it should not perform the default actions for this event.

For example, the onclick handler of a form submit button might return false to prevent the browser from submitting the form. (This can be useful if the user's input fails client-side validation.) Similarly, an input field's onkeypress event handler can filter keyboard input by returning false when invalid characters are entered.

Also important is the value returned by the Window object's onbeforeunload handler. This event is generated when the browser navigates to another page. If this handler returns a string, it will be displayed in a modal dialog box prompting the user to confirm that they want to leave the page.

It is important to understand that the return values ​​of event handlers are only counted if the handlers are registered by setting properties. Handlers registered with addEventListener() or attachEvent() must instead call the preventDefault() method or set the event object's returnValue property.

Canceling events

The value returned by an event handler registered as a property can be used to override the browser's default actions in the event of that event. In browsers that support the addEventListener() method, default actions can also be overridden by calling the event object's preventDefault() method. However, in IE version 8 and below, the same effect is achieved by setting the event object's returnValue property to false.

The following snippet demonstrates a hyperlink click event handler that uses all three methods of canceling the event (blocking the user from following the link):

Window.onload = function() ( // Find all links var a_href = document.getElementsByTagName("a"); // Add a click event handler (not for IE

The current DOM Events 3 module project defines a property on the Event object called defaultPrevented . It is not yet supported by all browsers, but its essence is that under normal conditions it is false and only becomes true if the preventDefault() method is called.

Canceling the default actions associated with an event is just one type of canceling an event. It is also possible to stop the event from spreading. In browsers that support the addEventListener() method, the event object has a stopPropagation() method, which when called stops further propagation of the event. If other handlers for this event are registered on the same target object, then the remaining handlers will still be called, but no other event handlers on other objects will be called after the stopPropagation() method is called.

In IE version 8 and below, the stopPropagation() method is not supported. Instead, the event object in IE has a property cancelBubble. Setting this property to true prevents the event from propagating.

The current draft of the DOM Events 3 specification defines another method on the Event object, a method called stopImmediatePropagation(). Like the stopPropagation() method, it prevents the event from propagating to any other objects. But in addition, it also prevents any other event handlers registered on the same object from being called.

One of the most important features of the JavaScript language, which is perhaps the main one in this language, is the ability to process some events. This feature is a feature for JavaScript compared to other web programming languages, because only this language can do this.

What is an event and event handlers

An event is an action that can be performed either by the user or other objects on the page.

The most striking example of an event is the user clicking on some object( click), be it a button, link or any other element. Another example of an event is hovering the mouse over some object( mouseover), say above the image. Also the event is the complete loading of the page( load). In general, all actions that occur on the site are events.

So, we can capture any event that occurs on the page and process it using the appropriate handler. For example, when you hover the mouse over a div block, we can display a certain message, for example, “You are in the text area.” Or, when you click on a button, hide a block from the page. In general, a lot of things can be done before processing an event.

And in order to process an event, you need to use a special handler for this event. Each event has its own handler, for example, the click event( click) there is a handler onclick. The event of mouse over an object( mouseover) there is a handler onmouseover. And the page full load event( load) there is a handler onload.

That is, as you understand, the name of the handler is formed from the prefix “on” + the name of the event.

A complete list of events and handlers can be found in the reference book; in this article we will consider only those that are most often used.

The event handler is called as an attribute within the HTML element tag itself. You can immediately write JavaScript code into the handler value, but it is better to call some function that will perform the necessary actions. The function must be described inside a script tag, which can be located either inside the head block or at the end of the body tag. The word this, that is, the current object, is passed as a parameter to this function.

Now let's write a simple example. When you hover the mouse over a block with text, we will display a message using the alert method indicating that the user is inside the text area.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Div( padding-left: 50px; width: 200px; border: 1px solid #000; )

JavaScript code:

Function blockOver(block)( alert("You are in the text area "); )

We save the document, open it in the browser, hover the mouse cursor over the text and see the result of processing this event:


How to get the value of an attribute in javascript?

Using the function parameter (this), you can get the value of some attribute of the current object, for example, find out its id.

For example, let's create a button and give it an id with the value "justButton". When we click on this button, we will display the following message: “You clicked on the button with the identifier value_id.” Here you need to already use the onclick handler.

JavaScript code:

Function clickOnButton(button)( alert("You clicked on a button with identifier: " + button.id); )

Save the document, open it in the browser and click on the button.


In the same way you can display the name of the button( button.name) or its value( button.value)

Getting the width and height of an element

You can also find out the values ​​of CSS properties of an element, for example, width and height. The clientWidth and offsetWidth properties are used to get the width, and the clientHeight and offsetHeight properties are used to get the height. For example, let's display the width and height of the button that was clicked.

Now the contents of the clickOnButton function will be like this:

Function clickOnButton(button)( //alert("You clicked on a button with ID: " + button.id); var width = button.clientWidth || button.offsetWidth; var height = button.clientHeight || button.offsetHeight; alert("Button width: " + width + "\nButton height: " + height);

The result of this example:


Let me remind you that the width of the element is calculated together with the padding value, so it is equal to 111px [ 99px(width) + 6px(padding-left) + 6px(padding-right) ].

If you don’t need to write a lot of code to process an event, you can write this code directly into the handler value. That is, instead of calling a function, we immediately write the necessary code.

For example, when a page loads, you can display a message that "page is loading." To do this, you need to use the load event and its onload handler. We will write this handler in the opening body tag.

This method can only be used if only one short line of code is needed to process the event. Otherwise, if the processing code consists of one long line or many lines, then you need to use a function.

And at the end of this article, we’ll look at a simple example of form processing. Processing the form in JavaScript, firstly, reduces the load on the server and, secondly, gives an additional advantage to the usability of the site.

The form consists of one login field and a submit button. When submitting the form, we will check the login length. Its length must be more than three characters.

Let's start with the HTML structure of this form.

Now, let’s add an onsubmit handler for the submit event as an attribute to the form tag. In the following way:

The submit event fires when the form is submitted. We wrote the return statement to prevent the form from being submitted if an error is detected in the data entry. If the function returns false, then the value of the onsubmit handler will be “return false”, which means that the form will not be sent to the server. Otherwise, if the form returns true, then the value of the handler will be “return true” and the form will be submitted without problems.

Sometimes it is necessary to completely disable form submission, in which case the value of the onsubmit handler will be like this:

Onsubmit = "checkForm(this); return false;"

As you probably already guessed, checkForm is the name of the function that will be called when the submit event fires. You can call it whatever you want, following the function naming conventions.

And so, let's return to our example. Now we need to describe the checkForm function. It will contain the following condition: if the login length is less than three characters, then we return false and the form will not be sent, otherwise, if the data was entered correctly, then we send the form to the server.

Function checkForm(form)( //Get the value of the form field whose name is login var login = form.login.value; //Check if the login length is less than three characters, then display an error message and cancel submitting the form. if(login .length > 3)( alert("Login length must be more than three characters"); return false; )else( return true; ) )

We save the document, open it in the browser and test it.


In this way, you can check the form in JavaScript and cancel its submission in case of an error.

Well, that’s all, dear readers. Let's summarize.
Events are used very often, so you must be able to work with them 100%.

In this article you learned what an event and an event handler are. You learned how to get element attribute values ​​and how to find the width and height of an element. You also learned how to perform form validation.

Tasks
  • Create a simple number adding calculator.
    • Create a form with two numeric fields (type="number") for entering numbers and a button labeled "Add"
    • When you click the submit button, call the function for processing this event.
    • Inside the function, get the field values ​​and using the alert method, display the result of adding the entered numbers.
    • Make sure that the form is not submitted after clicking the button.
  • onClick is the #1 event on the user's screen.
    onСlick is a click (or click) by the user on an object.
    After each such user onclick, a response action should occur on the screen. This achieves interactivity of the interface and confirms the main principle of communication between a computer and a person - click, answer, click, answer.
    In user jargon, the onСlick event can be called anything you like. As soon as ordinary users do not call this poor onСlick - click, pull, click, click, bang, etc. ... But the essence of this has not changed for years - if the user is active on the screen and clicks on an object, then the computer must respond adequately to him (the user). This is onСlick.

    onclick in HTML

    The onСlick event is of paramount importance in any language. And HTML is no exception to this. It is known. Indeed, if after clicking (onClick) on an element nothing happens in the browser, then why bother programming anything on the site at all? So, onСlick is a welcome guest on any Internet screen (or little screen).
    Now, closer to the topic. More specifically, our onClick on a website page in the browser is an event from a Java script, for which HTML serves only as a framework for placing the code of its constructs. And, from the point of view of the validity of the code of this very HTML, it would be correct to write onclick and not onСlick (as many application programmers are used to). Because in HTML all tags and structures are written only in lowercase.

    There is no uppercase in HTML. No, that's all! And for those “evil ones” who write in HTML in upper case, in the good old days it was customary to chop off their hands right down to their knees. Moreover. They say that under Father Tsar Ivan the Terrible, for writing in HTML, something like this could easily land you, if not impaled, then on the gallows. This is absolutely accurate. Right now, of course, the courtiers and rulers have become calmer. However, when writing any code, you need to observe at least the appearance of decency. From this place the story about the correct onclick begins.

    So, it's decided and proven (for HTML).
    First of all, we write onclick, not onСlick!!!

    MENU No. 1
    or
    MENU No. 1

    We will figure out what these crazy lines mean a little later, but for now...
    - Fundamentally, the onclick event from a Java script in HTML can be attached to any code element of an HTML page, be it ,

    Or . The browser will “devour” everything, and everything will work. The only thing is that access to an element from the keyboard is possible only for a link or button object. And, if we assume for a moment that the user does not have a mouse and works exclusively with the keyboard, then all that he will be able to touch on the site will be only buttons or links. There is no third! Therefore, “attaching” the onclick event to objects that are not accessible from the keyboard is simply ugly. Well, not humanly, somehow. This brings up the second rule for onclick in HTML - this event needs to be connected only to a link (the “a” tag) or a button (the “button” tag). Otherwise, the code will still work, but in hell, a separate large frying pan has been prepared for such programmers.
    Since (in HTML) formatting and working with buttons (“loaves”) causes certain difficulties, the only, universal and the best option only the link remains (tag “a”). But even with this tag, not everything is so smooth. Now, let's return to the analysis with our line of code:

    MENU No. 1

    We throw out the title links from the discussion as a completely obvious thing. It remains
    MENU No. 1
    All further writing will be related to the topic of blocking the href attribute, which needs to be properly “paralyzed” so that the link ceases to be a working link, but nevertheless performs the functions of onclick .

    return false;

    return false ; - This is a direct blocking of the href attribute. If the user has Java script enabled in the browser, then the onclick event will be called from the corresponding script, rather than following the link. That is, so that when you click on the “call link” there is no immediate transition to the address from the href, the return false event is added to onclick; and it is assumed that a function will be executed first that will cancel the link if javascript is enabled. Thus, the content of the href attribute has no meaning as it is ignored when the java script is executed.

    But here's the question. What happens if the user has Java script disabled (disabled) in his browser? How will our link behave then? I won’t intrigue you, but I’ll post it right away possible options developments of events - possible values ​​of the href attribute and the corresponding behavior of the browser after clicking on such a link when the Java script is turned off.
    Of course, if javascript is turned off in the user’s browser, this is one problem and a nuisance. If the execution of Java scripts is disabled (prohibited) in the user’s browser, then continuous problems begin with the href attribute, since the “a” tag is still a link and the browser will try to navigate to it.

    You cannot completely remove the href attribute from the link. It is impossible to do without the href attribute in the link text, and any validator will immediately be offended for such an outrage against her spicy and delicate body. This means that then there is only one option left - to fill the href attribute with digestible content. Here the following is possible: leave the href completely empty, fill it with a sharp “#” sign or javascript expression://. When the Java script is turned off (or glitched), after clicking on such links the following will happen:

    Test The href attribute is empty. After clicking on such a link, the page in the browser will simply reload. Sample The href attribute has the value "#". After clicking on such a link, the user will be thrown to the top of the page, without reloading it. Try The href attribute has the value "javascript://". After clicking on such a link, nothing will happen. href="javascript://" - clicking on the link will be simply ignored by the browser. The "javascript://" value for the href attribute is a standard "stub" for blocking a link when the Java script is turned off.

    href="javascript://" - bullshit!

    Why bullshit? Because, Internet life in the world search engines makes his own adjustments. From a correct and semantic point of view! layout, it would be absolutely logical to write a real link in the href attribute and add a real title for this link. Then, after clicking on such a link, one of two things will happen: either the onclick event from the corresponding Java script will be executed, or a transition will take place via the real link to real page, (if the Java script is disabled or glitched/underloaded).

    Thus, let's summarize. In the link for calling the Java script event, in href we place a real link to the real page to go to when javascript is turned off, and in onclick - a function that calls a request to execute the script when Java script is turned on.

    In other words, the “href” should contain a completely normal and working link to any web page to which the user will be redirected when clicking on the “event call link” turned off Java script, and which will be ignored by the script when included Java script. That's all …

    Well, in the end -

    Checking the browser to turn it on/off Java script

    The standard code for such a check looks like this:
    You have javascript disabled...
    Where, for you can write any styles in CSS, except display:none; and similar styles... A browser is a MUST!!! will display this message on the screen if the user disables the Java script in his browser. In this simple way, Webmasters often write: “Please enable javascript,” or display some beautiful pictures with a similar request, or something else... Inside the tag noscript You can place any HTML tags. And this is not an unnecessary precaution. Despite the fact that now it is not so easy to find a site that does not use javascript at all.

    He who is not with us is against us
    The problem with Java script turned off in the browser can, in general, be solved radically and radically. For example, add HTML5 code inside the section, like:




    where, http://mysite.ru/ is a web page to which it is immediately redirected
    user when turned off in the browser Java script.

    Greetings to everyone who wants to understand the functioning of onclick(). Today's article will help you understand the operating principle once and for all. of this handler events and sort out specific example onclick JavaScript, or rather examples.

    I will show you several ways to work with this tool, explain their advantages and disadvantages, and also describe jQuery work with events. Now let's move on to analyzing the material!

    Assigning Event Handlers

    First, let's look at the theoretical part of the question. Almost everyone processes scripts on their pages. And usually these are different events. In order for all of these programmed events to fire, a handler must be installed for them.

    According to the rules of writing, all handlers include “on+event name” in their name, which is observed in onclick(). Depending on the selected event, processing will occur due to different actions. In our case, when using onclick(), only those events that were caused by the left mouse click will be executed.

    Different ways to assign an event handler

    Today, there are several options for introducing a handler for certain events or events into the code.

    Using Simple Events

    Let's start with simple option, which consists of embedding onclick() into the markup of the html document itself. It looks like this:

    As you can see, when you click on the button with the left mouse button, the message “Click-click!” appears. I would like to draw your attention to one small but significant detail. You can only use single quotes ('') inside an alert.

    also in in this case can be used keyword this. It refers to the current element and provides all the methods available to it.

    Click on me

    This line of code creates a button with the text "Click on me". After pressing, you will see a message on the screen: ““Press!” It will replace the first name of the button.

    This method is undoubtedly very simple. However, it is only suitable for similar tasks, i.e. display messages or execute simple commands.

    If it is necessary to use cyclic structures, use tags, etc., then this method doesn't fit. It will reduce the readability of the code and also make it bulky and sloppy.

    In this case, you should resort to functions.

    Working with functions

    Functions allow you to separate required code into a separate block, which can later be called through an event handler in .

    As an example, I attached an application to display to the user the resulting number in various powers, starting from 1st and ending with 5th. To do this, I created a function countPow(), which can be passed parameters. In my application, the user must enter a number as a function variable.

    Thus, through the handler associated with the above-named function, calculations were performed and displayed on the screen.

    var result =1; function countPow(n) ( for(var i=1; i