I am trying to implement a click tracking on a page with some ajax calls, based on JWPlayer's opensource "Showcase" solution.
The page is basically a list of videos, and when clicking to see a video, the bottom video recommendations changes.
I have jquery selectors that works just fine, but when the content changes, the clicktracking do not works anymore. My original was to define a function. Calling it immediately for the first time, and then triggering it on click on the current elements + a delay.... but that last one do not works....
Any ideas?
var tc_r_clc = function() {
// BLOC TEXT
$(".jw-card-title").on("click", function () {
var v = $(this).closest(".jw-card-title").text();
var y = $(this).closest(".jw-card-title").attr('href');
alert(v + "---" + y);
});
};
// FIRST TIME
tc_r_clc();
// REFRESH ON CLICKS
$(".jw-card-controls, .jw-card-description, .jw-card-title, .jw-button-link").on("click", function () {
window.setTimeout(tc_r_clc, 500);
});
Have you tried with event delegation? From jQuery docs:
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Basically change your selectors where you attach events, like this:
$(document).on("click", ".jw-card-title", function () {
// your code...
})