Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3938668
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T00:12:40+00:00 2026-05-20T00:12:40+00:00

I have a Javascript plugin that searches the DOM for any elements starting with

  • 0

I have a Javascript plugin that searches the DOM for any elements starting with the class name “tracking” and adds a click event listener (or another type of listener, if specified) to that element. The idea is that every time that event occurs on that element, that it runs a Javascript function that sends data to our traffic servers. Here’s what the code looks like:

// Once the page is completed loaded
window.mmload(function() {      
    // Get the container object
    obj = document.getElementById(name);

    if ( obj.length < 0 )
        throw ("The Id passed into the tracker does not exist ("+name+")");

    // Find all the elements belonging to the tracking class 
    var trackingClass = new RegExp( /tracking\[[a-zA-Z0-9\.\-_]+\]/g );
    var myElements = getElementsByRegex( trackingClass, obj );

    //For each of those elements...
    for( var i in myElements ) {
        var elm = myElements[i];
        var method = elm.className.match( /tracking\[[a-zA-Z0-9\.\-_]+\]/ )[0].split('[')[1].replace(']','').split('.')[2];
        method = typeof( method ) == 'undefined' ? 'click' : method;

        // Add a click event listener
        myElements[i].addEventListener( method, function(e){
            // Get the element, the link (if any), and the args of the event                
            var link = elm.getAttribute('href') == null ? "" : elm.getAttribute('href');
            var args = elm.className.match( /tracking\[[a-zA-Z0-9\.\-_]+\]/ )[0].split('[')[1].replace(']','').split('.');

            // If a link existed, pause it, for now
            if ( link != '' )
                e.preventDefault();

            // Track the event
            eventTracker( args[0], args[1], ( method == 'click' ? 'redirect' : 'default' ), link );

            return false;
        }, true);
    }
});

Right now I’ve got this chuck of code running once the window has completely loaded (window.mmload() is a function I made for appending window.onload events). However, there maybe times when I need to run this function again because I added new elements to the DOM via Javascript with this class name and I want to track them too.

My initial solution was to run this function using setInterval to check the DOM every few milliseconds or second or whatever makes the most sense. However, I was worried if I took this approach that it might slow down the website, especially since this is running on a mobile website for smartphones. I’m not sure what kind of a performance hit I might take if I’m searching to DOM every so often.

The other approach I had in mind was to simply call the function after adding traceable elements to the DOM. This is probably the most efficient way of handling it. However, the people that I’m working with, granted very smart individuals, are Web Designers who don’t often think about nor understand very well code. So the simpler I can make this, the better. That’s why I liked the setInterval approach because nothing additional would be required of them. But if it noticeably slows down the site, I might have to take the other approach.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T00:12:40+00:00Added an answer on May 20, 2026 at 12:12 am

    You should consider even delegation.

    You just add one event listener to the document root and check the class of the element the event originated from (event.target). If you want to include also clicks from descendants, you’d have to traverse the DOM up form the target and check whether any of the ancestors contains the class.

    I see two main advantages:

    • It works for newly generated elements without any extra steps (so the other developers don’t have to do anything special).
    • It adds only one event handler instead of potentially many, which saves memory.

    Disadvantages:

    • If other event handlers are registered along the path and they prevent the event from bubbling up, you cannot register this event.

    A bit more information:

    An event handler gets an event object as first argument. This object has several properties, among others, which element the event originated form.

    E.g. to get the target element:

    var element = event.target || event.srcElement;
    

    This will be a DOM element and you can access the classes via element.className.

    So your event listener could look like this (note that IE uses another method to attach event listeners and the event object is not passed but available via window.event):

    function handler(event) {
        event = event || window.event;
        var target = event.target || event.srcElement;
        if(target.className.match(/tracking\[[a-zA-Z0-9\.\-_]+\]/g) {
            // do your stuff
        }
    }
    
    if(document.addEventListener) {
       document.addEventListener('click', handler, false);
    }
    else {
       document.attachEvent('onclick', handler);
    }
    

    But as I said, this would miss events that are prevented from bubbling up. At least in the browsers following the W3C model (so not IE), you can handle the events in the capture phase by setting the last parameter to true:

    document.addEventListener('click', handler, true);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a javascript function that manipulates the DOM when it is called (adds
I have a JavaScript resource that has the possibility of being edited at any
I have a JavaScript class that I have made and put it into its
I have a javascript function (class) that takes a function reference as one paremter.
I have a project that adds elements to an AutoCad drawing. I noticed that
I have a JavaScript method that I need to run on one of my
We have a JavaScript function named move which does just windows.location.href = any given
I have a JavaScript snippet that runs very well on Firefox and Safari, but
I have a javascript routine that is performing actions on a group of checkboxes,
I'm working on a lightbox style javascript plugin that pops up an image with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.