user192632 user192632 - 1 month ago 6
Javascript Question

Using "this" for click event of an html class

I was hoping to set up a click event in one line of code for all html tags that have a specific class name. Apparently it doesn't recognize

this
as an html object or container that references itself and myFunction never executes on any click. I am trying to use
this
because I want to search inside the tag that was clicked for other html elements, and I would rather the tags not have to have unique ids and click events for each one because there are many of these.

$(document).ready(){
$(".myClass").click(function () {
toggleDriver(this);
});
};

function toggleDriver(driver) {
zoomed = false;
$("#zoomer").css("display", "none");
map.fitBounds(bounds);
var dContainers = $("orders").find(".driverSection"); // first find all driver sections and loop through each
for (var x = 0; x < dContainers.length; x++) {
var tContainer = $(dContainers[x] + " .transactions"); // find transaction section for this driver section
if (dContainers[x].attr('id') == $(driver).attr('id')) { // is this the driver section that was clicked?
if ($(tContainer).css("display") == "none"){ // if collapsed
$(tContainer).slideDown("fast"); // expand it
exp = $(driver).attr("id"); // save which driver is expanded in global var
setDeliveryMarkers(); // set the map with driver marker and his delivery markers
}
else {
$(tContainer).slideUp("fast"); // it was expanded so collapse it
exp = ""; // save the fact that no driver transactions are expanded
if (trans != "") { //any transaction for this driver that had focus (white border) needs to lose it
$("#" + trans).css("border-color", "transparent");
// we need to stop the marker animation for this transaction that no longer has focus
for (var x = 0; x < deliveryMarkers.length; x++) {
if (deliveryMarkers[x].getTitle() == trans) {
deliveryMarkers[x].setAnimation(null);
break;
}
}
}
trans = ""; // clear this value to show that no transactions are in focus
setDriverMarkers(); // since no transaction section is expanded, show all drivers markers instead
}
}
else {
$(tContainer).css("display", "none"); // transaction container is not inside clicked driver section so close it
}
}
}


Does anybody know a better way to achieve what I want? Seems like just one small detail I'm missing. Thx.

POST EDIT: These html tags with this class name are loaded after document.ready so maybe someone can offer an answer geared towards that potential problem. Thx.

Answer

Since the elements are dynamically loaded, you will need to use Event Delegation

It would look like the following:

$(function () {
  $(document).on("click", ".myClass", function () { 
       toggleDriver(this); 
   });
});
Comments