MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

What are the Browser Events in Javascript?

In this article we will discuss about the browser events in Javascript. Javascript events are very important as they perform most of the tasks.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction:

A browser event is a signal from the browser to the application in case an action is performed. These events are of following types:

  • DOM Events: These are initiated by the DOM elements e.g. a click event is triggered when an element is clicked or a mouseover event is triggered when the mouse pointer is hovered on an element. These events connect a java script code with the document.
  • Window Events: These are initiated when the browser window is resized.

What are the events?

An event can be defined as an action/work that sends a signal to java script. Now java script executes in response to some event. But the event should be registered to send signal to the respective java script component. Following are some of the events.

Window events: These events are initiated when browser window is resized.

DOM events: These are initiated when a DOM element is performing some action.

Other events: These events are considering all other types of events apart from the above two.

Event handlers: We need to understand that there is a big difference between java and java script. In java, multi threading is possible but java script events are single threaded. So the event handlers are executed sequentially. To clarify it, let us assume one user has performed two events, mouseover and then mousemove. So the mouseover event will be executed first. Once the first event is complete, mousemove event will get executed.

If a script has to perform an action against an event, it should have a function associated to it. These functions are referred as event handlers. Usually these functions are named in the format – on+EVENT_NAME e.g. onclick etc. Event handlers in java script are single threaded and are executed sequentially. Hence if two events occur at the same time, their handlers will be executed one after other. There are many ways in which the event handlers are assigned. These are.

Using HTML tag: The event handler can be associated directly in to the markup using attribute onevent.

Listing 1: Event handler using html tag

<input id = "b1" value = "Click me" onclick = "alert('Thanks! I am clicked. '); " type = "button" />

When this code is executed, we see a button with a label - 'Click me’. If the user hits this button an alert window with a message - Thanks! I am clicked. We can also call a function for event handling. Consider the following code

Listing 2: Event handler using function

<!DOCTYPE HTML>
	<html>
	  <head>
	    <script type="text/javascript">
	      function count_rabbits() {
	        for(var i = 1; i <= 3; i++) {
	          alert( "Rabbit "+i+" out of the hat!" )
	        }
	      }
	    </script>
	 </head>
	 <body>
	 <input type = "button" onclick = "count_rabbits()" value = "Count rabbits!"/>
	 </body>

	</html>

Another approach to bind the event is using this.innerHTML where this refers to the current element. The following code illustrates this

Listing 3: Event handler using this.innerHTML

<button onclick = "alert ( this.innerHTML )"> Click me to see me </button>

Using DOM Object Property: Here the assignment is made using the property - onevent. In this case we need to get the element first and then assign a handler to the property onevent. The following code is an example of setting a click handler to the element with id 'myId' .

Listing 4: Event handler using DOM Object Property

<input id = "myId" type = "button" value = "Press me"/>
<script>
document.getElementById( ' myId ' ).onclick = function() {
    alert('Thanks')
}
</script>

Here the following two things must be noted in order to use this:

  • It is a property, not an attribute and its name is onevent which is case sensitive and should be in lower case.
  • The handler should be a function not a String.

When the browser finds an onevent attribute in the HTML markup, it creates a function using its contents and assigns it to the property. So the following two codes does the same.

Listing 5: Event handler using only HTML

<input type = "button" onclick = "alert( 'Click!' )" value = "Button"/>

Listing 6: Event handler using HTML & JS.

<input type = "button" id = "button" value = "Button"/>
<script>
 document.getElementById('button').onclick = function() {
     alert('Click!')
 }
</script> 

JavaScript overwrites a handler set in markup. The following snippet replaces a markup handler with a new one.

Listing 7: Overwriting a handler set.

<input type="button" onclick="alert('Before')" value="Press me"/>
<script>
document.getElementsByTagName('input')[0].onclick = function() {
  alert('After')
}
</script>

Using Special methods: In a complex JavaScript application, where different interface methods handle common event custom methods are used to assign handlers. Microsoft provides a solution which only works with IE version less than 9 and also with Opera. Handlers are assigned and detached as under Attaching a Handler

Listing 8: Attaching and removing handlers

element.attachEvent( "on" + event, handler)
Removing a Handler -
element.detachEvent( "on" + event, handler) 

Using attach event, we can assign multiple handlers to the same element. The following code snippet shows this.

Listing 9: Assigning multiple handlers to one element.

<input id = "myElement" type = "button" value = "Press me" />
<script>
  var myElement = document.getElementById( "myElement" )
  var handler = function() {
    alert( 'Thanks!' )
  }
  var handler2 = function() {
    alert( 'Thanks again!' )
  }
  myElement.attachEvent( "onclick", handler)
  myElement.attachEvent( "onclick", handler2)
</script>

Attach events doesn't pass the parameter 'this’. As per the W3C standard the following handler assignment works in almost all browsers that are used today.

Attaching a Handler

Listing 8: Attaching and removing handlers as per w3c

element.addEventListener ( event, handler, phase )

Removing a Handler

element. removeEventListener ( event, handler, phase ) 

Event related actions: We should take care of the following four actions while handling event related actions:

Register the event handler: This can be done by setting the elements onevent property e.g. onclick or onkeypress etc. This works with the entire browser but has a limitation that we can attach only one event handler to an element. The attached events can be removed in a similar fashion using detachEvent or removeEventListener.

Get the event object: Majority of browsers pass the event object as an argument to the handler. The following three events are generated when the user clicks his mouse.

  • Mousedown: indicates that the mouse is pressed.
  • Mouseup: indicates that the mouse is released.
  • Click: indicates that the mouse is clicked. If this happens in succession, this indicates that a double click has happened.

Extract information from the object - The third step is the extract action related information from the object and initiate the action.

Inform about the completion of the event - This is the final step. Once the event is auctioned successfully the completion of the event is marked.

Conclusion

To conclude the discussion we can keep the following points in mind:

  • An event is a signal from the front end to the back end.
  • Used to initiate an action which should be performed as per the customers need.
  • Events are of two types - DOM events and Window events.
  • Event handlers are functions associated to events.
  • Event handlers are assigned in the following way:
    • Using HTML tag
    • Using DOM object property
    • Using special methods


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login