Introduction to browser events in JavaScript

java-script-browser-events

Overview: In this article we will discuss about the browser events in JavaScript. Java script events are very important as they perform most of the tasks. The other important point is the browser compatibility. As the java script is embedded in html files, the execution of java script is browser dependent. Java scripts are also matured enough to handle browser events.

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 mouse over 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 on-event.

Listing 1:  Event handler using html tag

[Code]

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

[/Code]
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
[Code]

<!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>[/Code]Another approach to bind the event is using this.innerHTML where this refers to the current element. The following code illustrates thisListing 3: Event handler using this.innerHTML

[Code]

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

[/Code] 

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

[Code]

<input id = “myId” type = “button” value = “Press me”/>

<script>

document.getElementById( ‘ myId ‘ ).onclick = function() {

alert(‘Thanks’)

}

</script>

[/Code]

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

[Code]

<input type = “button” onclick = “alert( ‘Click!’ )” value = “Button”/>

[/Code]

Listing 6: Event handler using HTML & JS.

[Code]

<input type = “button” id = “button” value = “Button”/>

<script>

document.getElementById(‘button’).onclick = function() {

alert(‘Click!’)

}

</script>

[/Code] 

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

Listing 7: Overwriting a handler set.
[Code]

<input type=”button” onclick=”alert(‘Before’)” value=”Press me”/>

<script>

document.getElementsByTagName(‘input’)[0].onclick = function() {

alert(‘After’)

}

</script>

[/Code] 

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
[Code]

element.attachEvent( “on” + event, handler)

[/Code]

Removing a Handler –

[Code]

element.detachEvent( “on” + event, handler)

[/Code]

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.

[Code]

<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>

[/Code] 

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 10: Attaching and removing handlers as per w3c
[Code]

element.addEventListener ( event, handler, phase )

[/Code]
Removing a Handler
[Code]

element. removeEventListener ( event, handler, phase )

[/Code]








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.

o   Mousedown: indicates that the mouse is pressed.

o   Mouseup: indicates that the mouse is released.

o   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.

Summary: 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

o   Using HTML tag

o   Using DOM object property

o   Using special methods

READ MORE JAVA SCRIPT ARTICLES

Java Script Design Patterns

Java Script Design Patterns

Java Script Design Patterns

CSS3 & JavaScript

CSS3 & JavaScript

Java Script and CSS3 properties

 

Tagged on:
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share