Friday, June 17, 2022

Hack 9. Track User Events with Custom Data


Tracking user events can be difficult on highly dynamic pages with JavaScript alone. It usually requires that you add and remove multiple listeners. With HTML5 custom data, you can have that same rich interaction on dynamic pages with a single listener.

One of the most difficult things about generating HTML markup with JavaScript is managing behaviors. Anyone who has worked with DOM events on a dynamic app knows that managing behaviors can be quite a hassle. This hack shows you a way to use custom data along with JavaScript event delegation to make an otherwise difficult task easy and lightweight.

We’re not going to talk too much about event delegation; there are plenty of books and other resources out there that explain the details behind all of that. But it is important to know what event delegation is and why we do it.

Event delegation is the act of passing (or bubbling, to use a more accurate term) the captured event from an inner element to an outer element. Think about what happens when you click a button that is inside a list element (li). Since the button is inside the li, technically you clicked on both elements, so the browser by default passes or “bubbles” that click up from the button to the li. First the button executes its onclick event, and then the li executes its own onclick event. Event delegation is when you allow your event (in this case, the click event) to bubble up to a parent element (in this case, the li), which then fires an event based on the fact that you clicked on the button.

Generally, event delegation allows you to use fewer event listeners on a page, as any one listener can handle an endless number of functions based on the different elements being clicked. Using event delegation generally uses less memory in your page, and makes maintenance of dynamic pages much simpler.

In this hack we will add a tool tip to a list of elements using custom data and only one event listener.

Let’s start with our markup:

  <div class="container">

    <h1>Choose Your weapon</h1>
    <p>
     Click on one of the selections below to find out more info
     about your character:
   </p>

    <ul id="myList">
      <li data-description="Most powerful goblin in entire kingdom" >Ludo
</li>
      <li data-description="Ruler over all goblins big and small" >
       Jareth the Goblin King
      </li>
      <li data-description="Only person who can put a stop to the Goblin 
King" >
       Sarah
      </li>
      <li data-description="Unsung hero of the goblin kingdom" >
       Hoggle
      </li>
    </ul>
   <p id="displayTarg" class="well"></p>
  </div> <!-- /container -->

Figure 1-13 shows the results.

Figure 1-13. Our simple content

Custom data attributes allow us to “inline” data in our elements by setting a string to the data- attribute of the element. (For a more in-depth look at custom data, see [Hack #8].)

We are using an HTML5 page “primer” (the base page that we edit to get a quick start on development) called twitter bootstrap. It provides us with the clean look and feel for our markup; some of our additional class names come from that framework. Now let’s add our listener to the unordered list (ul) so that we can take action on any of the items inside it:

    var mainElement = document.getElementById('myList');
    var descriptionTarget = document.getElementById('displayTarg');
    mainElement.addEventListener('click', function(e){
        var description = e.target.getAttribute('data-description');
//remember we use getAttribute instead of
//dataset.description due to its backwards compatibility
        descriptionTarget.innerHTML = description;
        });

JavaScript event delegation is so much more powerful when you have access to additional data within the DOM element itself. Now imagine that this data was pulled from a database or JSON (JavaScript Object Notation) object and updated in the DOM. The list and markup can be updated, but the JavaScript does not need to change. The same listener can handle this list of four characters or a list of 400 characters, no matter how many times the list changes.

Can It Get Any Easier?

As markup gets more complex and we start to see elements nested inside other elements, finding the right target element to pull our description from can get pretty complicated. We are lucky to have many fine frameworks on the market that make event delegation easy to manage. Instead of managing the event target (e.target in the previous code) to get ahold of the right element, these frameworks allow us to write a few lines of code to make sure we’re working with the right elements. Let’s look at a few examples just to see how easy it is:

  • YUI (Yahoo! User Interface) Library version 3.0 and later

    Y.one('#myList').delegate('click', function(e){...}, 'li');
  • jQuery Library version 1.7 and later

    $("myList").on("click", "li", function(e) {...});

Embrace JavaScript event delegation, and make your markup more powerful with custom data attributes. You’ll find yourself writing less code, taking up less memory, and living an overall happier life!



 


SHARE THIS

Author:

urdufundastory.blogspot.com is the first of its kind of trendsetting venture existent in Pakistan. It is for the first time in the history of this nation that a large scale project of such nature, evolved from an extraordinarily revolutionizing concept to a practical fulfillment.

0 Comments: