1

Well, I'm trying to set an onClick event with jQuery on a image to open it on another tab after left click it. But it looks like because the website has lazy loading images, my script is not working. Even with the awesome waitForKeyElements script, which most of the times save me when the page has AJAX'ed content, I couldn't achieve what I'm looking for.

Please check my code below:

// ==UserScript==
// @include     https://revista*.globo.com/*.html
// @version     1.0
// @require     https://code.jquery.com/jquery-2.2.3.min.js
// @require     https://gist.githubusercontent.com/BrockA/2625891/raw/9c97aa67ff9c5d56be34a55ad6c18a314e5eb548/waitForKeyElements.js
// @grant       GM_openInTab
// @run-at      document-idle
// ==/UserScript==

waitForKeyElements("image.lazy-loaded.lazy-loaded", clickableImage, false);

function clickableImage (jNode) {

     jNode.each ( function () {
         var jThis = $(this);
         console.log( JSON.stringify( jThis ) );
         var imgLink = jThis.prop ("data-src");
         console.log( imgLink );

         jThis.on( "click", function() {

             GM_openInTab(imgLink);

         });


     } );

}

I'm using Firefox v68.0.1 with Tampermonkey v4.9.5941

Thanks in advance.


As this answer from the duplicate question explains and the comment, I achieved what I expected with the code below

waitForKeyElements("image.lazy-loaded.lazy-loaded", clickableImage, false);

function clickableImage (jNode) {

     var imgLink = jNode.data ("src");   
     jNode.on( "click", function() {

         GM_openInTab(imgLink);

     });
};
Commentator
  • 640
  • 1
  • 6
  • 22
  • i guess settimeout won't work in this case? – Keith Aug 01 '19 at 19:00
  • 1
    Thanks for the suggestion. I've tried, since WaitForKeyElements is based on setInterval I couldn't see how it could show different results. – Commentator Aug 01 '19 at 19:07
  • 1
    `"data-src` is not a property, it is a data attribute -- a special subset of attributes that are handled separately by both browsers and by jQuery. Use `var imgLink = jThis.data ("src");`. That's the biggest problem with that code but there are several others. For example WFKE only ever passes one node at a time to the callback. So, `jNode` will always be length 1 and `.each()` is a waste of effort. – Brock Adams Aug 01 '19 at 20:39
  • 1
    God bless you Brock Adams. Thank you now it worked. – Commentator Aug 01 '19 at 22:24
  • You're welcome; glad to help. – Brock Adams Aug 02 '19 at 00:41

1 Answers1

0

You can use on to bind event handlers to elements that don't yet exist. For example if the elements can be eventually found using the jQuery selector .lazy-loaded, then you can bind one event handler on a parent element that does exist already (like body) and events will be caught by the handler when they eventually bubble up later:

$("body").on("click", ".lazy-loaded", function() {
  alert("clicked");
});
Stephen Crosby
  • 1,157
  • 7
  • 19