How to JavaScript ‘this’ and Event Handlers

View: 333    Dowload: 0   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

9 point/2 review File has been tested

If there’s one reason to rely on a JavaScript library such as jQuery, it’s event handling. Most libraries abstract events into a uniform set of objects and handlers which work in most modern browsers. But we don’t need a library — we’re hardcore JavaScript developers!

Events 101

Without events and handlers, we would never be able to create slick client-side web applications. Events allow JavaScript to detect when a certain action has been performed by the user, e.g. hovering over an element, clicking a link, scrolling the page, resizing the window, dragging an object or any other activity.

Your JavaScript code can register a handler function which is triggered when a particular event occurs. Most browsers pass a single object to the function which contains information about the event, i.e. what keys were pressed, the position of the cursor, etc. It’s then possible to take certain actions such as animating an element, making an Ajax call, or preventing the browser’s default action.

In addition, ‘this’ may be set. You can normally expect it to be the element which fired the event, but that’s not always the case…

Inline events

These were the first event handlers browsers supported:

<p><a id="link" href="#" onclick="EventHandler();">click me</a></p>

<script>
function EventHandler() {
 console.log(this);
}
</script>

In this case, we’re simply running a function when the onclick event occurs and ‘this’ will be the global window object. We can make a minor change to our inline handler so the <a> element is passed:

<p><a id="link" href="#" onclick="return EventHandler(this);">click me</a></p>

Note that we’ve also added ‘return’. If our EventHandler returns false, the click event will be canceled.

important: Never use inline event handlers!

I’ve said this before but it needs repeating. Inline event handlers are limited, clunky, and can bulk up your HTML code. They cause maintenance complications since the invoking of the event and its handler are defined in different places. Finally, script tags must be placed at the top of your HTML rather than the bottom because an event could be called as the page is loading.

Traditional DOM0 events

Here’s our example using traditional event handling:

<p><a id="link" href="#">click me</a></p>

<script>
var link = document.getElementById("link");
link.onclick = EventHandler;

function EventHandler() {
 console.log(this.id);
}
</script>

In EventHandler(), every browser sets ‘this’ to the element which fired the event — our anchor tag. It’s reliable but has a major drawback: we can only assign a single handler for each event type.

note: Drop the parenthesis!

Be careful not to use link.onclick = EventHandler(); — EventHandler will be run immediately and the value returned (undefined) will be assigned to the onclick property of the #link node. It may not throw an error, but your handler will never be called when the click event occurs.

Modern DOM2 events

Finally, we have modern event handling which allows multiple handlers to be specified for the same event. Unfortunately, Microsoft and the W3C had a few differences of opinion with regard to their implementation and only IE9 supports addEventListener(). We can, however, use a little object detection to create a cross-browser event-attaching function which works in all browsers:

<p><a id="link" href="#">click me</a></p>

<script>
var link = document.getElementById("link");
AttachEvent(link, "click", EventHandler);

function AttachEvent(element, type, handler) {
 if (element.addEventListener) element.addEventListener(type, handler, false);
 else element.attachEvent("on"+type, handler);
}

function EventHandler(e) {
 console.log(this);
}
</script>

As with DOM0, all browsers set ‘this’ to the element which fired the event … except one. Internet Explorer 8.0 and below only reference the event handler so ‘this’ is always the global window object.

Fortunately we can determine the target element from the event object instead:

function EventHandler(e) {
 e = e || window.event;
 var target = e.target || e.srcElement;
 console.log(target);
}

Phew. And you wondered why jQuery became so popular!

 

How to JavaScript ‘this’ and Event Handlers

How to JavaScript ‘this’ and Event Handlers Posted on 22-04-2016  If there’s one reason to rely on a JavaScript library such as jQuery, it’s event handling. Most libraries abstract events into a uniform set of objects and handlers which work in most modern browsers 4.5/10 333

Comment:

To comment you must be logged in members.

Files with category

  • AngularJS and REST API

    AngularJS and REST API

    View: 57    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 85    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 57    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 64    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 260    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

  • Iteration Over Java Collections with High Performance

    Iteration Over Java Collections with High Performance

    View: 53    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Java developers usually deal with Collections such as ArrayList, HashSet, Java 8 come with lambda and streaming API helps us to easily work with Collections. In most cases, we work with few thousands of items and performance isn't a concern. But in...

  • SR2JLIB - A Symbolic Regression Library for Java

    SR2JLIB - A Symbolic Regression Library for Java

    View: 58    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Grammar-Guided Genetic Programming library featuring: multi-threading, just-in-time compilation of individuals, dynamic class loading, and JNI interfacing with C/C++ code

  • Yet Another Fluent JDBC Wrapper in 200 Lines of Code

    Yet Another Fluent JDBC Wrapper in 200 Lines of Code

    View: 72    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Those who are not convinced to use Hibernate to manage persistence are forced to use plain old JDBC API. Though powerful, it requires lot of typing to get it right. For example, retrieving user data from database often requires such code snippet:

 
File suggestion for you
File top downloads
Codetitle.net - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.net Develope by Vinagon .Ltd