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);
Related
I'm trying to modify specific images as the site displays a lower resolution file than the original, and also replace the link href for that image -- appending something to the end of that link to make it downloadable.
The website in particular, does not properly send the information about the image to the browser when you right click/save (file saves as content.jpg), but they have a download link which does properly send the filename to the browser (All it does is append &dl=1 to the end of the URL)
I have found some example code, and modified it to do the img src changes I require, but am having issues appending to the link href.
There are many types of links on the page so specific URL replacement is required:
Clickable Links all over page (Don't touch):
example.com/view/UNIQUEID
Image Src (Low Res): example.com/subdir/preview?page=UNIQUEID
Image Src (Original Res): example.com/subdir/content?page=UNIQUEID
I only wish to change the image sources from content/preview to content/content to display the full resolution image in the browser, but also add an href link (this can be copied from the img src as its the same link, but also append something to the end of it without affecting any other links.)
Here's what I have so far which works for replacing the specific img src:
image = document.getElementsByTagName("img");
for (i = 0; i < image.length; i++) if (image[i].parentNode.href) {
//Remove onclick attribute, cancelling their own Image Viewer
image[i].parentNode.removeAttribute('onclick');
//Replace regular sized preview image, with the full sized image
image[i].src = image[i].src.replace('example.com/subdir/preview?page=','example.com/subdir/content?page=');
image[i].parentNode.removeAttribute('width');
image[i].parentNode.removeAttribute('height');
}
Now I've found that adding
image[i].parentNode.href = image[i].src + '&dl=1';
at the end of my current script works. But it affects every image, so it breaks a lot of other things.
Any suggestions to simply append &dl=1 to the end of the now replaced 'subdir/content?page=UNIQUEID' href links?
TLDR:
Looking to change:
<a href="http://example.com/subdir/content?page=12345" onclick="imageviewer.open(); return false;">
<img src="http://example.com/subdir/preview?page=12345&filename=this+is+the+filename.jpg">
</a>
into:
<a href="http://example.com/subdir/content?page=12345&dl=1">
<img src="http://example.com/subdir/content?page=12345&filename=this+is+the+filename.jpg">
</a>
This question is almost a duplicate of: How to relink/delink image URLs to point to the full image?
The trick is to use querySelectorAll() (or jQuery) to fine-tune which images are processed.
Also, I recommend not changing the image source (keeps page fast and saves bandwidth), but just rewriting the link. Once the link is rewritten, you can right-click to save larger versions of just the pics you are interested in. Or, you can then use the excellent DownThemAll extension to bulk download images by link.
In your case, code like this should work:
var thumbImgs = document.querySelectorAll ("a > img[src*='subdir/preview?']");
for (var J = thumbImgs.length-1; J >= 0; --J) {
var img = thumbImgs[J];
var link = img.parentNode;
var lnkTarg = link.href + "&dl=1";
link.href = lnkTarg;
link.removeAttribute ('onclick');
//-- Not recommnded to change thumbnail...
//var imgTarg = img.src.replace (/\/preview/, "/content");
//img.src = imgTarg;
}
<a href="http://example.com/subdir/content?page=12345" onclick="alert('I shouldn\'t fire on click!'); return false;">
<img alt="Target img 1" src="http://example.com/subdir/preview?page=12345&filename=filename_1.jpg">
</a><br>
<a href="http://example.com/subdir/content?page=aaa" onclick="alert('I shouldn\'t fire on click!'); return false;">
<img alt="Target img 2" src="http://example.com/subdir/preview?page=aaa&filename=filename_2.jpg">
</a><br>
<a href="http://example.com/some/random/link" onclick="alert('I should still fire on click!'); return false;">
alt="Img shouldn't be altered" <img src="http://example.com/some/random/image.jpg">
</a>
I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}
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.
I am developing one image gallery website, which may have thousands of photos in future. All the images comes from other Website / API or user uploads.
User uploaded images
<img src="../images/example.jpg" alt="" />
External Images
<img src="http://example.com/xyz.jpg" alt="" />
Let say, image deleted from external website. Is there a way to check photo exists from client side using jQuery / JavaScript etc?
What I think is
i) I hotlink the image from external website
ii) Image deleted from external website, when website first load, jquery will send me the dead link info to server using ajax etc
iii) I will fix the link.
Thanks in advance...
You could use the "onerror" event on your external images and create a server side script to handle the error and return a generic "image not found" image while you fix the issue.
Something like ...
onerror="this.src='/fiximage.php?q='+this.src;"
You could do something like this...
$(function() {
$(document).on("error", "img", function() {
// do something with $(this) here
});
});
That would detect broken images and allow you to do something about it.
You can use onerror event in this case.
var imgs = document.getElementsByTagName("img"),
img, i = 0;
while (img = imgs[i++]) {
img.onerror = function() {
// just an example for error reporting
Ajax.send("POST /image_error.php", {src:img.src});
// change img src
img.src = "images/error.jpg";
};
}
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>