Forum Discussion
I'm not sure about attaching GA to the page -- I will ping some LDN folks and see they can answer that better. I can help with your second question. Your assessment is correct -- Lithium's JS is stopping the event from bubbling up to your listener.
When you attach listeners with jQuery, you want to find the right balance between the element to attach and the selector to check. So here are two versions of your call, one at each extreme:
$(document).on("click", "#lia-body .lia-content .custom-search-wrapper .lia-autocomplete-container ul li a", ...);
This example attaches to the document, which is the top level. Almost all clicks anywhere on the document will bubble up to this level, and jQuery will then try to match the selector to see if it should handle the event. This is not ideal for performance, and it also means that any other listener can stop the event from bubbling up, so your listener may never run when you want it to. That's what's happening here -- two things you don't want.
$("#lia-body .lia-content .custom-search-wrapper .lia-autocomplete-container ul li a").on("click", null, ...);
This example does a query up front to find all the matching <a> elements on the page and then attaches a listener to each one individually. You get more listeners (more memory usage), and if any new <a>s enter the document after this, they won't have a listener on them, BUT there is a gain -- jQuery will only have to process click events on the <a>, not every click anywhere on the page. Finally, this makes your listener run earlier, which means it's less likely that some other event listener (e.g. Lithium's JS) will run first and get in the way.
Neither of these examples is probably ideal in most cases. The best balance usually would involve attaching to the most specific permanent element(s) on the page. So in this case, that might mean something like this:
$("#lia-body .lia-content .custom-search-wrapper .lia-autocomplete-container").on("click", "ul li a", ...);
If that still doesn't run, you might need to follow the second example and attach listeners directly on each <a> element, each time autocomplete results are generated (since they're new elements each time).
Thanks for your detailed answer! I tried all the examples, but none have worked just yet. The very last thing you said was to run the 2nd example, and attach a listener to every <a> element, every time the auto complete results are generated. I think that sounds like the best bet, but what would you recommend using as a trigger? What can I listen for that will trigger my script every time the autocomplete results are generated and appear in the DOM?
Also, none of my events have shown up on Google Analytics just yet, despite successful in-browser testing. It can take a few hours to show up sometimes, but just in case, if your LDN folks know anything about GA events inside Lithium, I'd love any info they have.
Thanks again!
Related Content
- 3 months ago
- 11 years ago