Reputation: 159
I have a script im currently using, the issue is that i have to add the script directly after every html img tag. So there is the same script in several different places throughout the site. I am wondering if it is possible to wrap this script in a simple function call, and i can just add the function throughout the site instead of the whole script.
EDIT: I should have mentioned. This is a lightbox for a Tumblr theme. photo_{PostID} is valid. photo_{PostID} retrieves the unique photo identifier so the lightbox will display the correct image. The script right now works 100% perfectly fine no doubt about that. I'm looking to turn it all into a simple 1 liner call function to use instead of needing to paste the script after every img tag. the script is below, thanks.
<script class="inline_embed" type="text/javascript">
var domain = document.domain,
photo_{PostID} = [{
"width": "{PhotoWidth-HighRes}",
"height": "{PhotoHeight-HighRes}",
"low_res": "{PhotoURL-250}",
"high_res": "{PhotoURL-HighRes}"
}];
function event_is_alt_key(e) {
return ((!e && window.event && (window.event.metaKey || window.event.altKey)) || (e && (e.metaKey || e.altKey)));
};
document.getElementById('photo_{PostID}').onclick = function (e) {
if (event_is_alt_key(e)) return true;
window.parent.Tumblr.Lightbox.init(photo_{PostID});
return false;
}
</script>
Upvotes: 0
Views: 544
Reputation: 27227
You tagged this question with [jquery] so I'm going to give an answer using jquery, even though your sample code doesn't use it.
Here's a fiddle: http://jsfiddle.net/u2f2b5qq/
Given a few images on the page, like this:
<img src="http://placehold.it/250x150">
<img src="http://placehold.it/200x250">
<img src="http://placehold.it/350x150">
<img src="http://placehold.it/150x50">
You can do some action on all of them once the page loads, like this:
$(function() {
$('img').each(function() {
$(this).on('click', function() {
alert('You clicked ' + $(this).attr('src'));
// window.parent.Tumblr.Lightbox.init(this);
});
});
});
What I've done is attach a click
handler to every image and alert
when it's clicked. You would replace that with your lightbox code.
I don't have a full understanding of how tumblr does its magic with interpolating those values, but I assume you could do something like this for each image. It attaches the Photo data to each image element, and then retrieves it later.
<img src="example.jpg" id="photo_{PostID}" data-width="{PhotoWidth-HighRes}" data-height="{PhotoHeight-HighRes}" data-low_res="{PhotoURL-250}" data-high_res="{PhotoURL-HighRes}" />
and then in the jquery kickoff:
$(function() {
$('img').on('click', function() {
var $img = $(this);
alert('You clicked ' + $img.attr('src'));
window.parent.Tumblr.Lightbox.init({
width: $img.data('width'),
height: $img.data('height'),
low_res: $img.data('low_res'),
high_res: $img.data('high_res')
});
});
});
Give that a shot.
Upvotes: 1