I’m having to switch lightbox scripts because the one I’m using isn’t responsive and the site is moving to a responsive layout. A lot of the site is in WordPress and the script I’m switching to doesn’t have a WordPress plugin. I figure all I really need to do is to use jQuery to insert a class into image links when they link to another image. The rest I can take care of in the header.php file. The amount of Javascript I know can be written on the back of a postage stamp, so I’d be very grateful if someone could please tell me if this will work (or if there’s a better way of doing it)?
If I add
<script src="http://code.jquery.com/jquery-latest.min.js.js"></script>
to the header plus a link to a .js file containing the following code
jQuery(document).ready(function() {
jQuery("a[href$='jpg'] img, a[href$='JPG'] img, a[href$='jpeg'] img, a[href$='JPEG'] img, a[href$='png'] img, a[href$='PNG'] img, a[href$='gif'] img, a[href$='GIF'] img").parent().addClass("theClass");
});
will it do the job? I don’t have a way of testing this except on the live site so I’d like to get it right first time if possible.
You can use this:
This will search every link and filter out the ones not pointing to an image, then applies a class to the image (avoid classes with capitals, use dashes
-
).The match is case-insensitive, so, it will match
a.JpG
as well asa.jpg
.The file extentions it matches are
jpg
,jpeg
,png
,apng
,gif
andbmp
.More can be added inside the parenthesis, separated by
|
.If you want to apply to the link the famous class, remove
.find('img')
.Now, why am I using
this.href && this.href.match()
instead of using the selectora[href]
?This is simply for a performance reason: to lighten the parsing on the selector, so it can use
document.getElementsByTagName('a')
. The checkthis.href
would be made anyway, but in an earlier stage, but the engine used to match elements would have to work a bit harder.I don’t think you need to do all that pattern matching. If you want to add a class to any images that are links, try:
This would only affect images wrapped in a link tag, but wouldn’t affect any other links, PDFs, etc.
Update
To target links where the href is an image, you can use something like this (add or change the extensions as needed):