can someone help me with an issue I’m having where I think my understanding of the $this keyword in JQuery is somewhat lacking? I have 3 images on a page and each of these are wrapped in an anchor link. I want to to loop through and get the url of the anchor link, then using .load I want to ajax load some content from that url and place it in the figcaption element for that image. I was certain that the following code would work, but what this does is replace the image with the ajax loaded content, not place the content inside the figcaption. It’s driving me crazy! This is what I have so far…
$( ".artist-preview a" ).each(function( ) {
var $pageUrl = $(this).attr("href");
var $result = $pageUrl.split("/");
var $param = $result[$result.length-2];
$(this, "figcaption").load("/" + $param + " .wp-block-media-text__content p");
});
2
Answers
I was able to answer this myself. The issue was that the figcaption is not part of $(this) it's actually a sibling so by changing the last line so it uses .sibling() I was able to get this working.
Here's the solution I've used. This also limits the characters and makes the entire containing element clickable so the user can access the interior landing page.
Unless you are fixed using jQuery then perhaps the following vanilla javascript might be of interest. I made certain assumptions as certain details were lacking from the question in terms of the markup of the source html