Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to add a class to image links without messing up when the link passes variables

OK so I was using a bit of jquery to select all the <a> tags on the page and if they link to an image file to add a zoom class to it for the purposes of a lightbox. This is the code which works

$(document).ready(function () {
$('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').addClass('zoom');
});

There is a problem with this though;

Say I have a link which just goes to another page but passes an image url as a GET variable in the URL the lightbox is activated as a result of this and fails because the link is not actually to an image. For example:

<a href="http://example.com/a-normal-page/?pic=http://example.com/pics/picture.jpg">Link text</a>

In the above instance the jQuery script will add the zoom class to this anchor even though it doesn't actually link to a picture. This wouldn't usually be an issue as you would leave the page to go to the link's destination before the lightbox has a chance to appear, but in times where a new tab/window is opened I get a failed lightbox coming up.

This is particularly prevalent on social media buttons such as Pinterest which passes an image url within the link.

[apologies for the title - I wasn't sure how best to phrase it. Please feel free to edit to something more suitable]

like image 922
harryg Avatar asked Nov 20 '25 19:11

harryg


1 Answers

you could add the zoom class only if href attribute doesn't contain a ? (or, in other words, a querystring is not included), e.g.

$(document).ready(function () {
    $('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').each(function() {
        if (this.href.indexOf('?') < 0) {
             $(this).addClass('zoom');
        }
    });
});
like image 152
Fabrizio Calderan Avatar answered Nov 23 '25 10:11

Fabrizio Calderan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!