Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handlers in JavaScript for a progressively enhanced `select` element

I have a progressively enhanced <select> element in HTML.

It uses the following form,

<ul>
  <li></li>
  <li></li>
  ...
</ul>

With the current implementation, the click event handler is attached to every li element.

Will this create a problem when you have, say, about 1000-2000 elements, will it be slower as compared to attaching a single event handler to the <ul> and picking necessary information from e.srcElement?

Current implementation:

There is the whole list of

<div>
  <select>
    //1000-2000 elements
    <option> </option>
  </select>
  <ul>
    //Mapping the values of the 1000-2000 option tags
    <li> </li>
  </ul>
</div>

The click event handler maps the selected li to its equivalent option, sets that as the selected item and triggers the change event for the select.

like image 239
painotpi Avatar asked Oct 21 '22 18:10

painotpi


1 Answers

First of all, 1000-2000 DOM nodes that toggles might be a problem on its own, regardless of how you attach click handlers.

It is generally good practice to delegate events, but not too far. The closest common ancestor that share the same functionality is most often the best.

I have doubts that using one event handler for each child element will have any noticable effect on performance or memory, but delegating the event just makes so much sense, also in regards to keeping a clean maintainable code base.

Also, by delegating the event you can freely add/remove children without worrying about attaching/detaching events.

Example:

var ul = document.getElementsByTagName('ul')[0] // Or similar...
ul.addEventListener('click', function(e) {
    if(e.target.nodeName != 'LI') return;
    var li = e.target
    // map li -> option
});

Of course you’ll need to use attachEvent and srcElement for legacy Internet Explorer support.

Side note: remember that native select boxes are accessible using the keyboard, etc., so you better not rely on just the click handler to create a "progressively enhanced" select box using UL/LI elements.

like image 52
David Hellsing Avatar answered Oct 23 '22 12:10

David Hellsing