cross browser download image with javascript/jquery [duplicate] - javascript

This question already has answers here:
Any fallback client-side solutions for the html5 download attribute?
(2 answers)
Closed 7 years ago.
I have an image that i want to download.
I tried doing this with an iframe and it did not work.
I tried doing it with a link with the HTML5 "download" attribute and it worked on chrome but on firefox it opend a new window.
my code:
var href = $("#largeImageContaier img").attr("src")
$("#dlpic").attr("href", href);
document.getElementById("dlpic").click()
html:
<a href="" id="dlpic" download="alternate-filename.png">
I want to download the image directly to the browser like the code above does in chrome but how do i make it do the same for other browsers, in this example firefox

If you're using FireFox, you should be able to use the download attribute
Try actually setting the href to something. After I did that, it worked in both Chrome and FireFox.
Download
MDN says that download is used for setting the name you want the resource to have when downloaded. You still need to provide a href.
Another thing to note about download according to MDN:
This attribute is only honored for links to resources with the same-origin.
If you want to check for download support without having to use any libraries, you can use:
var dlAttrSupported = (function () {
return !!("download" in document.createElement("a"));
}());

From http://webdesign.tutsplus.com/tutorials/quick-tip-using-the-html5-download-attribute--cms-23880
You can use Modernizr to detect if the browser supports it and alternatively display instructions under the link to tell the user to 'right click and save as.'
if ( ! Modernizr.adownload ) {
var $link = $('a');
$link.each(function() {
var $download = $(this).attr('download');
if (typeof $download !== typeof undefined && $download !== false) {
var $el = $('<div>').addClass('download-instruction').text('Right-click and select "Download Linked File"');
$el.insertAfter($(this));
}
});
}
Here's a list of which browsers support the HTML5 download attribute: http://caniuse.com/#search=download

Related

Target browser with java script to change a link

I am trying to target specific browsers and depending on the browser I would like to display different links. My issues is that I have some pdf portfolios but they will only open in IE and the rest of the browsers give a message to download adobe reader.
My test code:
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
//For Firefox
if (browser == 'Firefox') {
document.write('Download');
}
//For Safari
if (browser == 'Safari') {
document.write('<'+'a href="test.pdf" download="test.pdf">Download</a>');
}
//For Chrome
if (is_chrome) {
document.write('<'+'a href="test.pdf" download="test.pdf">Download</a>');
}
//For IE
if(document.documentMode) {
document.write('View PDF');
}
This is what I have pulled together from searching but is not working. I want to view the pdf if in IE or download it if it is in another browser.
Feature detection is recommended over browser detection but in your case I don't think that will help. Here is a good script to detect the browser: WhichBrowser

How to use window.location with randomized objects?

I've made a site that randomizes HTML videos or images just to practice my javascript.
I am trying to make it so that each time a video is randomized the URL location will change to represent the new video, this way users would be able to link directly to a video that was randomized.
Currently it only displays a static url that does not change whenever content is loaded.
Here is the obligatory codepen
Codepen
function chooseRandomVideoFromList() {
var i = Math.floor(Math.random() * currentList.length);
var video = currentList[i];
var $video = $('video');
// clear
$video.html('');
// <source src="" type="">
video.sources.forEach(function (source) {
var $source = $('<source>').attr('type', source.type).attr('src', source.src);
$video.append($source);
});
Any help or advice would be greatly appreciated, i've read the documentation and I am still stumped :S
Thanks guys!
You cannot directly write on the window.location.href property, but you may change your sites url with the html5 history api and pushstate.
Example:
history.pushState({}, "Stackoverflow", "http://stackoverflow.com");
This should work in all modern browsers, see: http://caniuse.com/#search=pushstate
More information on this topic could be found here: https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history
Though keep in mind you need also to listen on popstate events if you want the users to be able to use their browsers back and forward buttons. Also your server side code needs to handle the urls.
If you need to support older browsers or don't want the server side to be involved you could set the window.location.hash property instead which does not change the url itself but let you change the hash part of the current url, for example:
window.location.hash = "uri=stackoverflow.com";
This way you might store the Index of the video currently shown. When loading the page you might want to check if there's a value in "window.location.hash" and if it is a valid index for your videoFiles. If so you should play that video.
Example (insert in your starting code):
if (window.location.hash !== "") {
showSpecificVideoFromList(window.location.hash);
}
And this one in your chooseRandomVideoFromList:
window.location.hash=i;
Then implement your showSpecificVideoFromList in order to show the given index (and check for validity)

GIF Image Stops when "document.location.href"

I have this function in javascript :
function loadPage (url){
showLoadPageGif(); // visibility On
document.location.href = getPath + "/" + url ;
}
When I use this function , GIF image is displayed in the screen but not working .
someone has fought before, with this problem ? thnx
i recently ran into this issue using animated SVGs as background-images in pseudo elements. I purposefully put in a large delay on my webserver so i could stay on the current page after window.location = url; It was weird that all other CSS animations and hovers still worked, but the SVG cog just stuck.
After some playing around i found that the animations continued to run if, instead of changing window.location, i submitted a GET form.
var url;
//load & setup loading animation
//then generate and submit form with a slight delay
setTimeout(function(){
var new_form;
new_form = document.createElement('form');
new_form.method = 'GET';
new_form.action = url;
document.body.appendChild(new_form);
new_form.submit();
}, 100)
tested on safari 5.1, firefox 24, chrome 32
I assume you mean "GIF animation stops".
This is the correct behavior. Since you go to a new page, all resources for the old page are freed. This of course includes the GIF itself.
You don't "see" this happening because the browser doesn't waste any time rendering a blank page when you assign location.href.
What you need to do is use an AJAX to request the new page and then replace the whole DOM with the new one in the success handler.
There is a bug in IE6 which stops the animations when you start an AJAX request; to fix that, just assign the src attribute of the image again (i.e. img.src = img.src;) to restart them.
Which browser you're using ? I needed to do the same one time if you're using IE just do this :
var loadingFigure = $('#myImage');
var html = loadingFigure.html();
window.location.href = 'myImage';
loadingFigure.html(html);
For firefox is more complicated you need to use an iframe and do something like this :
<iframe id="myIframe" src="/images/busy.gif" scrolling="no" frameborder="0"></iframe>
$('#myIframe').attr('src', '/images/busy.gif');
window.location.href = 'mylocation'
$('#myIframe').attr('src', '/images/busy.gif');

Copying to clipboard using javascript/flash

I am currently working on a PHP/HTML/Javascript project and I am trying to automatically copy text to the user clipboard when they press a button.
I've done some research and found that this can be done easily in IE, but every other browser doesn't support this, so instead a flash file is embedded which does the copying. Howver, this doesn't seem to be working.
Below is the code that does the copying
function copyToClipboard()
{
//Copy to clipbord if IE
if (window.clipboardData && clipboardData.setData)
{
window.clipboardData.setData('text', 'I am copied');
}
else //other browsers
{
alert("other browser");
var flashcopier = 'flashcopier';
if(!document.getElementById(flashcopier)) {
var divholder = document.createElement('div');
divholder.id = flashcopier;
document.body.appendChild(divholder);
}
document.getElementById(flashcopier).innerHTML = '';
var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent('other browser copied')+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashcopier).innerHTML = divinfo;
}
}
It appears to be working fine when using IE, but when using Chrome, nothing gets copied to the clipboard. There aren't any errors either in the chrome development tools.
I know the flash file is embedded OK using the above code as, if I change the src to say clipboard.swf_rubbish then the chrome development console says its can't find the file.
Thanks for any help you can provide.
That solution no longer works with the release of Flash Player 10. Because of security restrictions on accessing clipboard data. You can find a workaround here

Javascript document.write() - Replace PNG with GIF?

The Scenario
I have an asp.net web application with a HTML/CSS front end.
This all works fine but in Internet Explorer 6, the transparent PNG's that I use within the site are not transparent due to the poor design of this particular browser.
Solutions Attempted
I've already attempted various IE6 PNG Transparency fixes that didn't work.
The Proposed Solution
I thought about using GIF Image replacements for when the website detects that the browser is IE6. I don't have any javascript experience but someone has mentioned that I could use the "document.write()" feature off javascript to replace the PNG's with GIF's of the same image when using IE6 as the browser.
The Question
Please could someone explain to me how I would go about doing this?
Baring in mind I have an understanding of C# etc. but no javascript knowledge. I'm only just starting out as a web developer so simple explanations would aid me greatly.
Thanks for the help.
Regards.
If we assume that
a) the gif files will have the same name and,
b) they already exist (you're not looking for some gif creator).
Then you just need to replace the src attribute for these files. This would be done onload, and doesn't require document.write(). Go with:
<!--[if lte IE 6]>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
};
</script>
-->
The nice thing about the above method is that it doesn't have to check if it's gif or png or jpg every time, because it simply won't replace it with .gif unless there is a .png. The bad thing is that if, for some reason, you have an image with .png in it (and I can't imagine why) but it isn't the file extension, it would replace that bit with .gif.
Hope that helps.
Have you tried jQuery's pngFix? It makes the PNG transparent for IE 6 and you don't need to maintain two sets of images (PNG and GIF).
Using it doesn't require much javascript knowledge, so it wouldn't hurt to take a look at it.
Let's say your img element has an id="my_img"
To detect if browser is IE6, use conditional comments. Further, add Javascript like this:
<!--[if IE 6]>
<script>
document.getElementById("my_img").src = "images/alternate.gif"
</script>
<![endif]-->
You might also like to have a look at this:
IE6 PNG transparency
Here is the code runs a replace on IE6 only:
window.onload = function() {
if(navigator.userAgent.match(/MSIE 6/) != null)) {
var images = document.getElementByTagName("img");
for (var i = 0; i < images.length; i++) {
var src = images[i];
if(src.match(/\.png$/)){ //endswith .png
images[i].src = src.replace(/\.png$/g,'.gif');
}
}
}
};
jQuery version of the replacement:
$(document).ready(function()
{
// List all PNG images
$("img[src$=.png]").each(function(i, img)
{
// Replace with GIF versions
img.src = img.src.replace(/\.png$/, '.gif')
});
});
W3Schools is a great place to start if you're wanting to learn javascript.
For example, take a look at the getElementsByTagName function...
There is also a browser detect function here
Good luck - hope that helps.

Categories