Search code examples
javascriptjqueryunobtrusive-javascript

Making this JS code unobtrusive. Writing an event listener for unknown id


I've been building out the functionality for this UI. These are a pair of tabs I want to write a listener for, to make my js unobtrusive. It was blocking me from going forward. Now that I'm refactoring, it's time to fix it. I want to write an event listener that gets the id of the tab that was clicked, and assigns it to a variable. This is what I have:

<ul id="gal">

   <li class="glyphicons camera active" onclick="pullActive(this.id);" id="viewAll"><a href="#" ><i></i> View all photos <strong>(43)    </strong></a>
   </li>
   <li class="glyphicons circle_plus tab-stacked" onclick="pullActive(this.id);" id="addPhotos"><a href="#"><i></i> <span>Add Photos</span></a>
   </li>
</ul>

function pullActive(id){

 // gets the class for that id
  var getClassy = document.getElementById(id).className;
  findClass(getClassy, id);
  loadNew();

}  

Solution

  • without jQuery you would have to do

    var item = document.querySelector("#gal");
    item.attachEventHandler("click", function(ev) {
       if (ev.target.tagName === "LI") {
          var id = ev.target.id;
          // ...
       }
    });
    

    In jquery (as you tagged your question like this) it would look like this

    $(function() {
       $("#gal").delegate("li", "click", function() {
          var id = this.id;
          // ...
       });
    });