Add lightbox effect to images automatically - javascript

Is it possible to add a lightbox effect automatically to every image which is embedded like this
<img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="">
to this
<img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="" title="">
after the page loaded successfully?
I would like to enable this on a Ghost CMS installation with JQuery support.
Thanks in advance!

You could have Javascript on every image in the page and then alter the attributes as necessary. Not necessarily the best approach (doing it server-side is preferred), but it can work. You will also, most likely, need to re-instantiate the lightbox plugin to reparse the page after you go through the images.
var img = jQuery("img");
img.each(function() {
var element = jQuery(this);
var a = jQuery("<a />", {href: element.attr("src"), "data-lightbox": "test"});
element.wrap(a);
});
http://jsfiddle.net/ak74A/1/
You'll need to add your own customized properties, but you get the idea.

additional to Jason idea, if you want to add lightbox to images without an anchor tag parent, we can add an if statement to check if the img parent is an anchor tag.
var img = jQuery("img");
img.each(function() {
var element = jQuery(this);
if( this.parentElement.tagName != "A" ){
var a = jQuery("<a />", {href: element.attr("src"), 'data-lightbox': 'Article image'});
element.wrap(a);
}
});

Related

Create an img element into <a> tag using javascript

I want to embed an image inside an tag after the image on tag loaded.
So the sequence goes like this...
<a id="anchorID">
<img onload="MyFunc(anchorID)>IMAGE1</img>
//..After image 1 loaded add
<img>IMAGE2</img>
</a>
<script>
function MyFunc(anchorID)
{
var anchorElement = document.getElementById(anchorID);
//I want to create an image tag inside the anchorElement
}
</script>
Thanks for the help.. T_T
Here's a solution, just add onload="addNextImage('#id_in_which_to_add_new_image', 'second_image_url')" to the image you want to load first. In the next example, ignore the width and style (I put them there to be able to test the functionality, making the image smaller so I don't need to scroll to see the behavior - I chose a huge image to make sure everything works as it should, and the border makes it appear sort of like a progress bar =)
<script>
function addNextImage(selector, url) {
var where = document.querySelector(selector);
if (where) {
var newImage = document.createElement('img');
newImage.src = url;
where.appendChild(newImage);
}
}
</script>
<a id="anchorID">
<img onload="addNextImage('#anchorID', 'http://animalia-life.com/data_images/wallpaper/tiger-wallpaper/tiger-wallpaper-01.jpg')" src="http://hubblesource.stsci.edu/events/iyafinale/support/documents/gal_cen-composite-9725x4862.png" width="400px" style="border: 1px solid black" />
</a>
This should work on most browsers today: IE8+ (as long as you use basic CSS2.1 selectors as the first argument), and pretty much everything else in use. (IE8+ because it depends on querySelector)
I think what you are looking for is
Javascript appendChild()
var node = document.createElement("img");//Create a <img> node
node.src="SomeImageURL";
firstImage.appendChild(node);
JQuery append()
$("#firstImageID").append("<img src="SomeImageURL"/>");
see links for more info
Javascript
jQuery
You can use the following to add an image to the anchor tag
function MyFunc(anchorID) {
var anchorElement = document.getElementById(anchorID);
if (anchorElement) {
//I want to create an image tag inside the anchorElement
var img = document.createElement("img");
img.setAttribute("src", "yourImagePath");
anchorElement.appendChild(img);
}
}
Hope that helps.

How to prevent an <img> tag from loading its image?

I have the following script which take a string with html information (containing also reference to images).
When I create a DOM element the content for the image is being downloaded by the browser. I would like to know if it is possible to stop this Beauvoir and temporary prevent loading.
I am targeting web-kit and presto browsers.
relativeToAbosluteImgUrls: function(html, absoluteUrl) {
var tempDom = document.createElement('div');
debugger
tempDom.innerHTML = html;
var imgs = tempDom.getElementsByTagName('img'), i = imgs.length;
while (i--) {
var srcRel = imgs[i].getAttribute('src');
imgs[i].setAttribute('src', absoluteUrl + srcRel);
}
return tempDom.innerHTML;
},
Store the src path into an HTML5 data-* attribute such as data-src. Without src being set, the browser will not download any images. When you are ready to download the image, simply get the URL from the data-src attribute and set it as the src attribute
$(function() {
// Only modify the images that have 'data-src' attribute
$('img[data-src]').each(function(){
var src = $(this).data('src');
// modify src however you need to, maybe make
// a function called 'getAbsoluteUrl'
$(this).prop('src', src);
});
});
The approach taken by popular image library, Slimmage, is to wrap your img tags in noscript tags:
<noscript class="img">
<img src="my-image.jpeg" />
</noscript>
Web scrapers and people with JS turned off will see the image as if the noscript wasn't there but other browsers will completely ignore the noscript and img tags.
You can then use JavaScript to do whatever you want with it, for example (using jQuery):
$('noscript.img').replaceWith(function(){
return $(this.innerText).removeAttr('src');
});
I think you should reverse the logic, don't load the images by default and at the moment the image is needed, update it's src attribute to tell browser to start loading.
Or even better way would be to use some jquery lazy image loading plugin like this one:
http://www.appelsiini.net/projects/lazyload
Hope this helps.
To prevent images from being show, you could use this.
$(window).loaded( function() {
$("img").removeAttr("src");
});
It might be tricky and give unexpected results, but it does it.

Determine file extension of a dynamic image's src

Working on a Greasemonkey script, that will take a certain action if the image loaded on a webpage is a gif or jpg. The code from the page is as follows:
<div id="current_photo">
<div style="text-align:center;">
<img src="[url]/[random numbers].gif/jpg" alt="" style="[styles]">
</div>
</div>
The start of the URL will be unique, as there is only one image on the page with that URL. Need a way to pull that path and get the extension from it.
The HTML in the question is malformed. Is that really an accurate snippet? Link to the target page.
Anyway, code like this should work:
var payloadImage = document.querySelector ("#current_photo div img");
if (/\.gif$/i.test (payloadImage.src) ) {
// DO GIF ACTION HERE
}
else if (/\.jpg$/i.test (payloadImage.src) ) {
// DO JPG ACTION HERE
}
else {
// DO WHATEVER HERE
}
Add id="something" for your image tag. Then something like this:
var path = document.getElementById('something').src;
var extidx = path.lastIndexOf('.');
var extension = path.substr(extidx+1);

Preloading images in Javascript

I have created a simple photo gallery viewer, and I would like to preload the images in the background, and then run a function when they are done.
My question is, how do I do that?
var image = new Image();
image.src = "http://foo.com/myimage.jpg";
//if you have a div on the page that's waiting for this image...
var div = getElementById("imageWrapperDiv");
//you can set it on the image object as the item to draw into...
image.myDiv = div;
image.onload = function(){
//do whatever you're going to do to display the image
//so in this example, because I have set this objects myDiv property to a div on the page
// I can then just populate that div with an img tag.
//it's not the most elegant solution, but you get the idea and can improve upon it easily
this.myDiv.innerHTML = "<img src='" + this.src +"'>";
}
Once the image loads, it's in the browser's cache, so, if you use the src property you can draw it anywhere on the page and it will display instantly.
To preload an image use the <link> tag and add preload to the rel-attribute:
<link rel=preload href=path/to/the/image.jpg as=image>
Alternatively in Javascript:
var preImg = document.createElement('link')
preImg.href = 'path/to/image.jpg'
preImg.rel = 'preload'
preImg.as = 'image'
document.head.appendChild(preImg)
The preload value of the element's rel attribute allows you to
write declarative fetch requests in your HTML , specifying
resources that your pages will need very soon after loading, which you
therefore want to start preloading early in the lifecycle of a page
load, before the browser's main rendering machinery kicks in. This
ensures that they are made available earlier and are less likely to
block the page's first render, leading to performance improvements.
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
I like this CSS method versus the typical Javascript function:
Place this in your CSS file:
div#preload { display: none; }
Place this at the bottom of your HTML document:
<div id="preload">
<img src="http://domain.tld/image-01.png" width="1" height="1" alt="Image 01" />
<img src="http://domain.tld/image-02.png" width="1" height="1" alt="Image 02" />
<img src="http://domain.tld/image-03.png" width="1" height="1" alt="Image 03" />
</div>
This method ensures that your images are preloaded and available for use elsewhere in the document. Just remember to use the same path as the the preloaded images.
http://perishablepress.com/pure-css-better-image-preloading-without-javascript/

jQuery, JavaScript, HTML: how to load images after everything else is loaded?

I have a very complex page with a lot of scripts and a rather long loading time. On top of that page I want to implement the jquery Nivo Slider (http://nivo.dev7studios.com/).
In the documentation it says I have to list all images for the slider inside of a div#slider
<div id="slider">
<img src="images/slide1.jpg" alt="" />
<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
<img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
<img src="images/slide4.jpg" alt="" />
</div>
However I might have 10 images with a 1000x400px which is quite big. Those images would load when the page loads. Since they are in my header this might take quite a while.
I looking for a way to use any jquery Slider Plugin (like the nivo slider) but either dynamically load images or load all those images after everything else on my page has loaded.
Any idea how I could solve that?
Is there even a way to start a javascript process after everything else on the page has loaded? If there is a way I might have an solution for my problem (using the jquery ajax load() method) ... However I have no idea how to wait for everything else to load and then start the slider with all the images.
Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.
Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.
Here's the code.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
In addition to Xhalent's answer, use the .append() function in jQuery to add them to the DOM:
Your HTML would just have:
<div id="slider">
</div>
And then your jquery would be:
jQuery(function(){
$("#slider").append('<img src="images/slide1.jpg" alt="" />');
});
check out jquery load() event, it waits for everything including graphics
$(window).load(function () {
// run code
});
on load you could then load the images using:
var image = new Image();
image.src = "/path/to/huge/file.jpg";
You can add a function onload to the image too
image.onload = function() {
...
}
I am using the below to power my slider and improve the page load performance.
for (var i = document.images.length - 1; i >= 0; i--) {
var this_image = document.images[i];
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
$(this_image).attr("src",lsrc);
}
}
}
the best way to use is b -lazy js.
bLazy is a lightweight lazy loading image script (less than 1.2KB minified and gzipped). It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data loaded if he/she doesn't browse the whole page.
For a full list of options, functions and examples go to the blog post: http://dinbror.dk/blog/blazy.
The following example is a lazy loading multi-serving responsive images example with a image callback :) If your device width is smaller than 420 px it'll serve a lighter and smaller version of the image. When an image has loaded it removes the loader in the callback.
In Html
<img class="b-lazy"
src="placeholder-image.jpg"
data-src="image.jpg"
data-src-small="small-image.jpg"
alt="Image description" />
In js
var bLazy = new Blazy({
breakpoints: [{
width: 420 // Max-width
, src: 'data-src-small'
}]
, success: function(element){
setTimeout(function(){
// We want to remove the loader gif now.
// First we find the parent container
// then we remove the "loading" class which holds the loader image
var parent = element.parentNode;
parent.className = parent.className.replace(/\bloading\b/,'');
}, 200);
}
});
Example
jquery has a syntax for executing javascript after document has loaded:
<script type="text/javascript">
jQuery(function(){
//your function implementation here...
});
</script>

Categories

Resources