Loading...

How to JavaScript ‘this’ and Event Handlers

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

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

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

Posted on 22-04-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 25    Download: 2   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 62    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 26    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 37    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 204    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: 168    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: 157    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: 169    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...

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