Force download an image from src using Javascript - javascript

I've an image tag with a parent div which contains image_wrap class. Now I want to download this image using javascript. I've got some solution to download this image, but this code is not working for me. Can anyone help me please?
Here is my code:
var img_wrap = $('.image_wrap'),
src = img_wrap.find('img').attr('src'),
anchor = '<a href="' + src + '" download></a>',
downloadable_tag = img_wrap.append(anchor);
downloadable_tag.click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image_wrap">
<img height="100px" width="200px" src="https://s3.envato.com/files/248564292/01_eduma.__large_preview.__large_preview.jpg" />
</div>

You have a few problems there in your code.
First, you are appending the wrong element to img_wrap element. You should be appending the anchor element instead of the downloadable_tag.
Then, .click() should be used on dom objects, not on Jquery objects. So I think you should fix that line too.
Finally, the download attribute will show the download window only for files which are in the same domain. It doesn't work for cross origin requests for security purposes.
So with all the mentioned fixes, this is how your code should be:
<div class="image_wrap">
<img height="100px" width="200px" src="01_eduma.__large_preview.__large_preview.jpg" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var img_wrap = $('.image_wrap'),
src = img_wrap.find('img').attr('src'),
anchor = $('<a href="' + src + '" download>hello</a>'),
downloadable_tag = img_wrap.append(anchor);
anchor[0].click()
Notice that I have used a local path for the image. Here's a plunker demo.
http://plnkr.co/edit/eK1yJTYPUzF5p4DVTRem?p=preview
Hope it helps :) Feel free to ask if you have any doubts!

Try following script:
http://jsfiddle.net/h4JXs/8928/
$(document).ready(function () {
var img_wrap = $('.image_wrap'),
src = img_wrap.find('img').attr('src'),
anchor = '<a href="' + src + '" download>hello</a>',
downloadable_tag = img_wrap.append(anchor);
downloadable_tag.trigger('click')
});

It seems you want to download the image rather than navigating it. The attribute download works only for same origin URLs. Check documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

You have assigned the same variable in the append statement
downloadable_tag = img_wrap.append(downloadable_tag);
Change it with the below one.
downloadable_tag = img_wrap.append(anchor);
var img_wrap = $('.image_wrap'),
src = img_wrap.find('img').attr('src'),
anchor = '<a href="' + src + '" download>hello</a>',
downloadable_tag = img_wrap.append(anchor);
downloadable_tag.click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image_wrap">
<img height="100px" width="200px" src="https://s3.envato.com/files/248564292/01_eduma.__large_preview.__large_preview.jpg" />
</div>

Related

How to safely use "&" symbol in a javascript variable without it turning to "&"?

I am trying to execute the following code:
<button onclick="increment()">Increment</button>
<div id="iframe">
<script>
var id = 139000;
var link='<iframe src="https://somewebsite.com/something.aspx?sa=1&pid=' + id + '" height="600px" width="100%" />';
function increment(){
id++;
document.getElementById('iframe').innerHTML = id + link ;
}
</script>
</div>
But while executing, the & in src="" converts to & which breaks the original URL and doesn't go to the desired destination. I looked up on the internet but as I am a noob, I was not able to figure it out. Please help me to make this work!
All you need to do is
<button onclick="increment()">Increment</button>
<div id="iframe">
<script>
var id = 139000;
var link='<iframe src="https://somewebsite.com/something.aspx?sa=1&pid=' + id +
'" height="600px" width="100%" />';
var new_link = link.replaceAll('&','&');
function increment(){
id++;
document.getElementById('iframe').innerHTML = id + new_link;
}
</script>
This is definitely a blogger issue, and the reason behind happening is :
The character "&" is an ISO HTML reserved character used to denote the start of a parameter.
To overcome this the Blogger editor translate the & you enter to the HTML entity, & , that will display & when the page or URL is rendered in a browser, so that you don't have to do it yourself.

How to make a popover that shows an enlarged version of a dynamic image using JQuery?

I have to display a popover containing an enlarged version of a dynamic image that gets added via a file input #insert-image but I am not sure how to go about doing this since the image is dynamic and the url of the image changes depending on what is selected by using the file input. The code below basically just adds the image that is selected to a table cell.
var imagePrep = $("#insert-image").val().replace(/C:\\fakepath\\/i, 'images/');
$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image'>");
I managed to get it working myself by adding a few attributes data-toggle='popover'" + "data-img=" + imagePrep + ">" with imagePrep being my variable. I also had to add a mouseover function to my image and within that function I added the popover using the popover function (ps. If you get an error saying that the popover function doesn't exist just make sure to have the bootstrap scripts in your html file, you cn find the bootstrap scripts on the bootstrap website).
This is a solution that solved my problem:
$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image' data-toggle='popover'" + "data-img=" + imagePrep + ">").on('mouseover', function() {
$('[data-toggle="popover"]').popover({
trigger: 'hover',
html: true,
content: function() {
return '<img class="img-fluid" src="' + $(this).data('img') + '" />';
},
title: 'Enlarged Image'
});
});
Hope this helps.
Just copy the commented url and pest in text box dynamic image is created. You also use both jQuery and Javascript attributes. Below is the example:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head><!--from ww w . ja v a2 s.c o m-->
<body>
<div>
<input type="text" id="insert-image" />
<input type="button" id="insert" value = "insert" />
</div>
<div id="imgwrapper"></div>
<script>
$(document).ready(function()
{
$("#insert").on("click",function(){
img = document.createElement("img");
// img.src = "http://www.java2s.com/style/download.png";
img.src = $('#insert-image').val();
img.mouseover = function(e){alert(e);}
$('#imgwrapper').append(img);
$("#imgwrapper").on("mouseover",function(){
alert("TEST");
});
});
});
</script>
</body>
</html>

How to get current window URL and use it?

I want to get current window location using JavaScript and use it in the following code:
<img src="http://shook.eu.org/qrc.php?text=CURRENT_WINDOW_URL" />
If you are building the html from a string:
var img = '<img src="http://shook.eu.org/qrc.php?text=' + encodeURI(window.location.href) + '" />';
document.body.innerHTML = img;
Edit: You should encodeURI the string you want to pass.
var url = window.location.href;
var img = '<img src="http://shook.eu.org/qrc.php?text='+url+'" />';
$('#img').html(img);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img"></div>

Can javascript set attributes like links and a title based on an ID of an image?

I'm building an image gallery with 600 thumbnail photos. All the thumbnails are the same size and they should all behave in the same way. Clicking on a thumbnail will bring up a small version of the image and there's an image magnifier called jQZoom that will let visitors see the photo in more detail. ( http://www.mind-projects.it/projects/jqzoom/ )
Here's the code I'm using for a typical thumbnail (number 462):
<a href='javascript:void(0);' title="Plate 462" rel="{gallery: 'gal1', smallimage: './Vol4/Small/tafel_462.jpg',largeimage: './Vol4/Large/tafel_462.jpg'}">
<img src="Vol4/Thumbs/tafel_462.jpg" width="94" height="150" border="0" /></a>
The problem is that it seems like a lot of code for what I'm trying to do. In particular, every time I add a thumbnail I have to type in the new image number 4 times (for the title and the sources of the 3 image sizes).
Isn't there a way I could just put in the image number once (as an ID or something) and have a javascript interpret that to assign the title and the three links?
What you think about a function to return the desired HTML?
function getImageThumb(src, title) {
return $('<a href="javascript:void(0);" title="' + title + '" rel="{gallery: \'gal1\', smallimage: \'./Vol4/Small/' + src + '.jpg\', largeimage: \'./Vol4/Large/' + src + '.jpg\'}">' +
'<img src="./Vol4/Thumbs/' + src + '.jpg" alt="' + title + '" width="94" height="150" border="0" /></a>');
}
So you can create each thumb like:
$("#container").append(getImageThumb('tafel_462', 'Plate 462'));
$("#container").append(getImageThumb('another_img', 'An Example'));
Yes, you can.
Your a html should have two attributes, let's say data-imgsrc, and data-gallery, and remove the a's rel attribute and the img's src attribute like this:
<a href='javascript:void(0);' title="Plate 462" data-gallery="gal1" data-imgsrc="tafel_462.jpg">
<img width="94" height="150" border="0" /></a>
Then you'd do:
$(document).ready(function(){
$("a[data-imgsrc]").each(function(){ //Customize your selector
var imgsrc = $(this).attr("data-imgsrc");
var relObj = {
"gallery": $(this).attr("data-gallery"),
"smallimage": "./Vol4/Small/"+imgsrc,
"largeimage": "./Vol4/Large/"+imgsrc
};
$(this).attr("rel", JSON.stringify(relObj));
$(this).find("img").attr("src", "Vol4/Thumbs/"+imgsrc);
});
});
If your gallery isn't variable, you could remove the data-gallery attribute and just put 'gallery1' in the js.
That's it.
Hope this helps. Cheers

Problem with .html() function in jQuery

Can anyone explain why this jQuery .html() function is not outputting anything?
I'm new too jQuery and cant seam to spot anything, if you can please tell me :D
I'll just include the html, nothing else:
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.scrollTo-1.4.2.js"></script>
<script type="text/javascript">
//when the DOM is ready
$(document).ready(function(){
var like_count = <?php print "23"; ?>;
//Scripts for getting number of comments for this post
var comment_count = <?php print "12"; ?>
var thumnail_path - "";
var time_ago - "";
//settings on top
var doindex = 'comments.php?item_id=';
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
//function that creates posts
var postHandler = function(postsJSON) {
$.each(postsJSON,function(i,post) {
//post url
var postURL = '' + doindex + post.item_id;
var id = 'post-' + post.ID;
//create the HTML
$('<div></div>')
.addClass('post')
.attr('id',id)
//Script for getting the number of likes for this post
//generate the HTML
.html('<table width="244" height="121" border="0" cellpadding="0" cellspacing="2" ><tr><td height="24" colspan="2" bgcolor="#0270B7"><table width="410" border="0"><tr> <td width="404" height="20" class="username"> ' + post.username + '<span class="name"> ' + post.name + '</span></td></tr></table></td></tr><tr> <td width="51" bgcolor="#Edeff4"><span class="thum"><img src="' + thumnail_path + '" alt="" width="50" height="50" /></span></td><td width="355" height="50" bgcolor="#Edeff4" class="content"> ' + post.item_content + '</td></tr><tr><td height="19" colspan="2" bgcolor="#Edeff4" class="content"> <span class="post-title">comment </span>(' + likecount + '<span class="post-title">)</span> <span class="post-title">likes (' + likecount + ') ' + time_ago + '</span></td></tr><tr><td height="18" colspan="2" class="content"> </td></tr></table>')
Thanks :))
Assuming you haven't left out part of your script, it doesn't look like you're ever adding your div to the body somewhere.
After your html call, put .appendTo('body'). Example:
$('<div></div>').html("Some stuff...").appendTo('body');
Of course, you can use whatever function you want to place it in the document.
Why would it output anything?
I'm not a jquery wizard, but I believe if you give .html information (as you are doing) it doesn't output anything, instead it loads that into the item specified.
aka:
$('body').html('<h1>TEST</h1>');
if you want to retrieve the html don't put anything between the parenthesis
var body = $('body').html();
Note: Not tested
I would look up information about jquery on visualjquery.com and http://api.jquery.com/category/selectors/basic-css-selectors/
<div id='output'></div>
<script>
$('#output').html('<your content>');
</script>
You must call the .html() function on something.
Check out this link :
.html()
I usually add HTML within a DIV by selecting it by its id. You might wanna try adding the html on another line, selecting the div by its id like that:
$('<div></div>').addClass('post').attr('id',id);
$('#'+id).html('blablabla');
I've not tested this. It it doesn't work, you can create an empty DIV like Arun David just said before and append the new DIV in.

Categories