javascript click event. JavaScript onclick event and three ways to handle events
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 unique to JavaScript compared to other languages from web programming, because only this language has the power to do something like this.
What is an event and event handlersAn 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 your mouse over something div block, we can display a message, say “You are in text area". Or, when you click on a button, hide some block from the page. In general, a lot of things can be done before processing some event.
And in order to process some event, you need to use a special handler for of 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, in the HTML tag element. You can immediately write to the handler value JavaScript code, but it is better to call some function that will do 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:
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, then 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 elementYou can also find out the meanings CSS properties element, such as 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 should be more than three characters.
Let's start with HTML structures 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 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.
This is how you can check the form for: JavaScript and cancel its sending 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 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.
Event Handling
JavaScript client programs are based on an event-driven programming model. 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 particular type of event for a particular document element, it can register one or more functions to be called when that event occurs. Keep in mind that this is not a unique feature of 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 case of events intended for a single object (such as the "load" event of a 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.
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 ; - This is a direct blocking of the href attribute. If the user has Java script enabled in his browser, 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 first be executed 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 navigate 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 scriptThe 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.
Let's look at the most standard and frequently used JavaScript events:
a, area, button, input, |
The current element loses focus. Occurs when |
|
Input, select, textarea |
Changing the values of form elements. Occurs after an element loses focus, i.e. after the blur event |
|
Almost everything |
Single click (mouse button pressed and released) |
|
a, area, button, input, label, select, textarea |
||
Almost everything |
Mouse button pressed within the current element |
|
Practically |
The mouse cursor is out of bounds |
|
Almost everything |
The mouse cursor is over the current element |
|
Almost everything |
Mouse button released within current element |
|
Moving a window |
||
Resizing a Window |
||
Select text in the current element |
||
Submitting form data |
||
Attempting to close the browser window and unload the document |
For execution following example we will need a new concept - event.
In our case, an event is the program’s reaction to a user action (mouse clicking on a button, shrinking the browser window with the mouse, entering text from the keyboard, etc.). Using the program, we have the opportunity to respond to any user actions.
Let's consider one of the most common events - onload - which occurs when a document is loaded (when the user, through his actions, causes the web page to load).
Let's look at an example of using the javascript onload event to change the width and height of an element.
Example: Add an image to a page and javascript help When the page load event occurs, make the image width match the width of the browser window
function resizeImg() ( var myImg= document.getElementById ("img1" ) ; myImg.style .width = document.body .clientWidth ; ) ... |
function resizeImg())( var myImg=document.getElementById("img1"); myImg.style.width=document.body.clientWidth; ) ...
In the example, the main actions occur in the resizeImg() function:
Task Js8_4. Place several images in the html code ( img tag). Using the method change:
— size (width and height properties) of all page images
— border size ( border property) all images.
Complete the code:
var allImg=document...; // get an array of images for (var i=0; i< allImg.length; i++){ allImg[i].....; // меняем свойство width ...; // меняем свойство height ...; // меняем border }
Event onclick JavaScript and three ways to handle eventsThe onClick event occurs when a mouse button is clicked once. Process the event, i.e. You can react to it using a script in three ways. Let's look at them:
Example: Clicking a button displays a dialog box with a message "Hooray!"
Script:
IN in this example in the html code we see a button. The button has an onclick attribute ( "on click"), the value of which is a call to a function called message() . This is a custom function described above in the script. In the function itself, a dialog box is displayed, which is what is specified according to the task.
The script for such event processing is usually located in the head area of the document
This is a simplified version of event handling; it is only suitable for small code when one or two statements need to be executed. Otherwise the code will be hard to read.
The button attribute is onclick ( "on click"), and as a value a script is written from operators indicating what language it is written in (javascript:). In our case, the operator for output modal window with the word "Hooray!"
html code:
Script:
document.myForm .myButton .onclick = message; function message() ( alert("Hurray!" ) ; ) |
document.myForm.myButton.onclick = message; function message() ( alert("Hurray!"); )
In the html code there is a button with an id attribute, which is necessary to access the button through a script.
In the script, which must be located below the tree of elements (possibly before closing the body tag), there is a call to the button (document.myForm.myButton), for which an onclick event handler is assigned with the value of a function link. A button can be accessed through the id attribute (document.getElementById("myButton").onclick = message;)
There are no parentheses after the function name message. IN in this case this is precisely a reference to a function, otherwise, when using parentheses, the function would be called rather than assigned as an event handler.
It is this way of processing events that is as close as possible to what happens, for example, in the Windows OS.
Task Js8_5. Complete the task according to the instructions:
Green
...seagreen
... magenta
...purple
...navy
...royalblue
Task Js8_7. Creating a rollover image
— Add a tag to the code img with image.
- Introduce event handlers onmouseover(by guidance) and onmouseout(during abduction). Do this as functions.
onmouseover loading procedure into the tag img another image.
- Attach to event handler onmouseout procedure for loading another image into a tag img.