Difference between HTML events and javascript events

There are many ways we can attach an event to an HTML element. First way: HTML attribute

<div id="foo" onclick="print2()> My event is attached as HTML attribute</div> 

The second way is to use some library (say jQuery)

 <div id="bar"> My event is attached using jQuery </div> <script> $("#bar").click(function() { alert("Hi this is Bar"); } </script> 

I used to think that jQuery can internally convert an event to the corresponding HTML attribute, but this does not happen. Check out http://jsfiddle.net/blunderboy/wp4RU/3/

I register all the foo and bar attributes, and there is no onclick attribute in the bar line. Please explain.

+4
source share
1 answer

There is nothing called HTML Event! The two types of events that you described are embedded events and unobtrusive events, and both are javascript events.

Embedded Events

When you declare javascript code for the elements themselves, it becomes an inline event . You have several common events (as attributes for HTML elements), such as onclick , onkeydown , onkeypress , onkeyup , and they all start with on . One such example:

 <a href="#" onclick="alert('You clicked me!')">Click Me!</a> 

Unobtrusive events

We need to assign something that will be executed when the event fires. The = symbol = always used in JavaScript to assign a value to the right of a method or property to the left.

A window is not the only object to which we can attach events. We can attach events to any object on a web page, provided that we have a way to uniquely identify this object. One way to identify an object is to provide it with an identifier and reference it with document.getElementById("id_of_the_element") .

Let's take the same example.

 <a href="#" id="clickme">Click Me!</a> 

Instead of the onclick attribute, I have an ID in the same place that uniquely identifies the HTML <a> element. Now I can get the id inside javascript as follows:

 document.getElementById('clickme'); 

To do this, I can attach an event handler that is not much different from how we use attributes. It just doesn't have on front. In the previous example, we used onclick , but now we just use click .

 document.getElementById('clickme').click = functionName; 

Here functionName refers to any javascript function name or anonymous function. So, for the warning, if we create a function called alertme() , we can define this method:

 function alertme() { alert('You clicked me!'); } 

Now you can attach a function to an element as follows:

 document.getElementById('clickme').click = alertme; 

Still feeling lazy, you can do this using an anonymous method that does not accept the name:

 document.getElementById('clickme').click = function () { alert('You clicked me!'); } 

I hope you understand. :) Let me know for further clarification.

+3
source

Source: https://habr.com/ru/post/1432624/


All Articles