Create download link based on img src Jquery - javascript

I have several different galleries of images that have image captions. I'm attempting to append a download link of the corresponding image to the end of each of the gallery captions. The download link needs to be based on the img src for each image.
I can get it to append the download link to the caption. However, it's also appending a download icon for each image contained in the gallery on every image caption. Instead of one download link per image.
HTML
<div>
<figure class="gallery-item">
<!-- BoGalleryImg -->
<div class="gallery-icon landscape">
<a href="http://creative.dev.j2noc.com/thehub/wp-content/uploads/2017/10/crkis-2515.jpg" data-rel="lightbox-gallery-1">
<img width="300" height="250" src="http://creative.dev.j2noc.com/thehub/wp-content/uploads/2017/10/crkis-2515.jpg" class="attachment-full size-full" alt="" aria-describedby="gallery-1-823">
</a>
</div>
<!-- EoGalleryImg -->
<!-- BoCaption -->
<figcaption class="wp-caption-text gallery-caption" id="gallery-1-823">
<a target="_blank" href="https://jira.j2noc.com/jira/browse/CRKIS-2515">
CRKIS-2515
</a>
</figcaption>
<!-- EoCaption -->
</figure>
<br />
<figure class="gallery-item">
<!-- BoGalleryImg -->
<div class="gallery-icon landscape">
<img width="300" height="250" src="http://creative.dev.j2noc.com/thehub/wp-content/uploads/2017/10/crkis-2379b.jpg" class="attachment-full size-full" alt="" aria-describedby="gallery-1-817">
</div>
<!-- EoGalleryImg -->
<!-- BoCaption -->
<figcaption class="wp-caption-text gallery-caption" id="gallery-1-817">
<a target="_blank" href="https://jira.j2noc.com/jira/browse/CRKIS-2379B">
CRKIS-2379B
</a>
</figcaption>
<!-- EoCaption -->
</figure>
</div>
jQuery
$(document).ready(function() {
$('.attachment-full').each(function(index, element){
// create variable from img src
var imgSrc = $(element).attr('src');
console.log(imgSrc);
//Append Download Link to Caption
$('.gallery-caption').append('</span>');
});
});
I have been trying to figure this out for a couple days now and I'm so close I'm just not sure how to get it to append only one download icon for the corresponding image. Thank you in advance for any help that can be provided.
My CODEPEN DEMO

Your html is a bit hairy to parse. Here is some jQuery that reproduces your output with the desired icon count:
images = ['http://srsounds.com/j3/images/easyblog_articles/2943/han_solo.jpg', 'https://lumiere-a.akamaihd.net/v1/images/chewie-db_2c0efea2.jpeg?region=0%2C154%2C1592%2C796'];
labels = ['CRKIS-2515', 'CRKIS-2379B']
images.forEach(function(value, index) {
$('body').append("<img src=" + value + " width=350><br>" + labels[index] + " <i class='fa fa-download' aria-hidden='true'></i><br><br>");
$('body').css('color', 'steelblue');
})
If you want to use these icons bring in awesome fonts:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
There may be other requirements in terms of your gallery layout, but hopefully this will help you get started on a cleaner approach.
If you're having issues adding link attributes to your icons, or achieving additional layouts let me know.
******** EDIT ********
If you want/need to stick with your original approach, then change your jQuery to this:
$(document).ready(function() {
download_ids_hold = [];
imgSrc_hold = [];
$('.attachment-full').each(function(index, element){
// create variable from img src
var imgSrc = $(element).attr('src');
imgSrc_hold.push(imgSrc)
console.log(imgSrc);
//Append Download Link to Caption
$('.gallery-caption').each(function(ind_2, elem_2) {
add_id = 'a_' + Math.floor((Math.random() * 100000) + 1);
download_ids_hold.push(add_id)
if(index == 0) {
$(this).append('<a id=' + add_id + ' download><i class="fa fa-download" aria-hidden="true"></i></span></a>');
}
})
});
for(id=0;id<download_ids_hold.length;id++) { $('#' + download_ids_hold[id]).attr('href', imgSrc_hold[id]) }
});
We track the image sources and download ids, and use them appropriately at the end.

Related

Image src is changing but the image is not updating in Internet explorer 11

Here is my code
$('.thumb-container-xs').click(function() {
///alert("You have clicked!");
var img = $(this).find('img');
var img_src = img.attr('src');
var img_title = img.attr('title');
var img_alt = img.attr('alt');
$("#productImage0").attr({
src: img_src + '?' + new Date().getTime(), //adding random number at the end of the src not working
title: img_title,
alt: img_alt
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 thumb-container clearfix" id="activeProductImgContainer">
<!--Big Image-->
<a href="#" class="img-bg" id="activeProductImgBg">
<img src="http://cdn3.wpbeginner.com/wp-content/uploads/2016/02/stocksnap.jpg" class="thumb-img img-thumbnail thumb-custom" id="productImage0" alt="Mypic" title="My pic">
</a>
</div>
<div class="clearfix">
<!---small images-->
<div class=" col-xs-3 thumb-container-xs">
<a class="img-bg-xs" id="productImage2" href="#"><img class="thumb-img-xs img-responsive thumb-custom" src="http://cdn3.wpbeginner.com/wp-content/uploads/2016/02/stocksnap.jpg" title="f" alt="f"></a>
</div>
<div class=" col-xs-3 thumb-container-xs">
<a class="img-bg-xs" id="productImage3" href="#"><img class="thumb-img-xs img-responsive thumb-custom" src="https://s3.amazonaws.com/media.spl/1353_bof.jpg" title="g" alt="h"></a>
</div>
<div class=" col-xs-3 thumb-container-xs">
<a class="img-bg-xs" id="productImage4" href="#"><img class="thumb-img-xs img-responsive thumb-custom" src="https://www.bensound.com/bensound-img/betterdays.jpg" title="h" alt="h"></a>
</div>
<div class=" col-xs-3 thumb-container-xs">
<a class="img-bg-xs" id="productImage5" href="#"><img class="thumb-img-xs img-responsive thumb-custom" src="https://www.bensound.com/bensound-img/littleplanet.jpg" title="i" alt="i"></a>
</div>
</div>
What the code actually does is update the big image whenever i click on a small image thumbnail.
Everything is working fine in Crome and firefox but not working in Internet Explorer. When I'm clicking on the small image thumbnail the 'src' of the image is changing but the image is not updating. How can I solve this issue?
I found the solution.No problem with my code.As internet explorer does not support object-fit css property,I had to hide the <img> tag and set a background-image property to it's parent which is #activeProductImgBg and what I did just changed the image src which is hidden in IE.But I had to change the background property of it's parent also at the same time.Now it's working fine.
Here is the additional code
$("#activeProductImgBg").css('background-image', 'url(' + img_src + ')');
Try running this code instead of yours and see if load() triggers. They claim with URLs fix you did (adding a seed in the end) it should work. I just don't have IE11 installed to test it out.
$('.thumb-container-xs').click(function() {
///alert("You have clicked!");
var img = $(this).find('img');
var img_src = img.attr('src');
var img_title = img.attr('title');
var img_alt = img.attr('alt');
$("#productImage0").attr({
src: img_src + '?' + new Date().getTime(), //adding random number at the end of the src not working
title: img_title,
alt: img_alt
});
$("#productImage1").attr({
src: img_src + '?' + new Date().getTime(), //adding random number at the end of the src not working
title: img_title,
alt: img_alt
});
$("#productImage0").load(function(){console.log(0)});
$("#productImage1").load(function(){console.log(1)});
});
If the images are not loaded console.logs will not fire, if they do then is a matter of refreshing the DOM.
This trick worked for me to force the browser to redraw the element, you hide show their parent in quick succession.
$('#activeProductImgContainer').hide().show(0);

Javascript dont take changed variable

I have a gallery function with an imagezoom at the big image.
When the big image is changed and i click on it to activate the zoom function, it shows the old image.
I think the variable isnt changed in javascript?
<script type="text/javascript">
function change_img(imgurl) {
image = document.getElementById('preview');
image.src = imgurl
imageURL = imgurl
}
$(document).ready(function(){
var imageURL = document.getElementById('preview').src;
$('#ex3').click(function() {
var imageURL = document.getElementById('preview').src
$('#ex3')
.zoom({ on:'click', magnify:1.8, url:imageURL })
.wrap('<span style="display:inline-block"></span>')
.css('display', 'block');
})
});
EDIT:
This way the thumbnails will be created:
<span class='zoom' id='ex3'>
<img id="preview" name="preview" src="default.jpg" border="0" align="center"/>
<span class="zoom-btn"></span>
</span>
<!-- BEGIN thumbs -->
<div class="thumbnails">
<img id="thumbimg" onclick="change_img('{PATH}/{thumbs.ID}')" name="img" src="{PATH}/{thumbs.ID}" alt="" />
</div>
<!-- END thumbs -->
In javascript .zoom it should be the changed path at "url:imageURL".
Anyone knows how to get the actual path in imageURL?
EDIT: Will this work?--I'm honestly not sure if this zoom function changes the img source or not. If it doesn't, changing that from here, should be fairly easy. There seemed, from a search, to be several of which you could be using.
<span class='zoom' id='ex3' data-src="changedimg.jpg">
<img id="preview" name="preview" src="default.jpg" border="0" align="center"/>
<span class="zoom-btn"></span>
</span>
<script type="text/javascript">
$(document).ready(function(){
$('#ex3').click(function() {
var newURL = this.data('src')
$('#ex3')
.zoom({ on:'click', magnify:1.8, url: newURL })
.wrap('<span style="display:inline-block"></span>')
.css('display', 'block');
})
});
</script>

jQuery append an img to every div

I am trying to display a thumbnail image with every thumb class, but currently I am getting the output below where the images are looping inside the href instead. The order of div, href and img must not change. It looks something like this jsfiddle but this isn't fully working of course...
currently getting:
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
<img src="">
<img src="">
</div>
required output:
<div class ='thumb'>
<a href="#" rel="1">
<img src=>
</a>
</div>
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
</div>
my loop:
var thumbnails = [];
$.each(data.productVariantImages,function(key, val){
thumbnails.push(val.imagePath);
});
for(var thumb in thumbnails) {
$('.thumb').append($('<img>').attr({
"src":[thumbnails[thumb]]
}));
}
am i looping it wrongly?
edit:
The thumbnails are part of a dynamic gallery where basically every time a user choose a different option in a dropdown list, the sources for the thumbs are supposed to change accordingly.
current html:
<div class="thumbnail"><?php
foreach($skuDetails['productVariantImages'] as $variantImage){
if(isset($variantImage) && $variantImage['visible']){
?>
<div class="thumb">
<a href="#" rel="1">
<img src="<?php echo $variantImage['imagePath']; ?>" id="thumb_<?php echo $variantImage['id']; ?>" alt="" />
</a>
</div> <?php }}?>
</div>
sample array of thumbnails:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
sample output:
<div class="thumbnail">
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
</div>
You need to use .each function on .thumb. Something like:
$(document).ready(function(){
$('.thumb').each(function(){
$(this).append($('<img>').attr({"src":[thumbnails[thumb]],}));
});
});
your loop is focused on wrong element. You append img tag to the thumb class. So, the img tags inside the same element. You should create div has thumb class inside the loop, and append it to the thumbnail div. That must like
var div = $(".thumbnail");
$.each(imageArray, function(index, value){
var elem = "<div class='thumb'><a href='#' rel='1'></div>";
div.append($elem);
$('.thumb').append("<img />").attr("src", value);
});
It may be wrong but you should watch the thumbnail element. I cannot write the code to test. But I think the logic must be like this.
If you want that exact structure, I made a demo using plain JavaScript. Enter a number and the thumbClone() function will generate that many. You could probably adapt this function with your existing code easily. I'm in rush, it probably needs refactoring, sorry. :-\
DEMO
function thumbClone(qty) {
var main = document.getElementById('main');
var aFig = document.createElement('figure');
var aLnk = document.createElement('a');
var aImg = document.createElement('img');
aLnk.appendChild(aImg);
aImg.src = "http://placehold.it/84x84/000/fff.png&text=THUMB"
aFig.appendChild(aLnk);
aLnk.setAttribute('rel', '1');
main.appendChild(aFig);
aFig.className = "thumb";
console.log('qty: ' + qty);
var thumb = document.querySelector('.thumb');
for (var i = 0; i < qty; i++) {
var clone = thumb.cloneNode(true);
thumb.parentNode.appendChild(clone);
}
}
You need to use each loop which will get each class rather than getting only one class below is syntax of each loop
$(selector).each(function(){
// do your stuff here
)};
in your case
$('.thumb a').each(function(){
// do your stuff here
$(this).append($('<img />').attr('src',[thumbnails[thumb]]);
)};
Looks like you need to create the entire div structure for each image.
Lets create the below structure dynamically using the max length of the image array and add the image src .
var thumbDivStart = "<div class ='thumb'><a href="#" rel="1">";
var thumbDivEnd = "</a></div>";
var thumbDiv = "";
for (i = 0; i < imageArray.length; i++) {
thumbDiv = thumbDivStart + "<img src="+imageArray[i]+"/>"+
thumbDivEnd;
//Here you can append the thumbDiv to the parent element wherever you need to add it.
}

jQuery find closest

I'm trying to get the a href of an list item.
HTML
<div class="popup" style="display: none;">
<div class="product">
<div class="photo">
<a href="" class="sendkleur" id="link69"> <!-- href im trying to reach -->
<img id="product-collection-image-69" src="" alt="Test kleur" class="popup-image69">
</a>
</div>
<a href="" class="sendkleur" id="link69">
<strong>Test kleur</strong>
</a>
<span class="swatchLabel-category">Kleur:</span>
<p class="float-clearer"></p>
<div class="swatch-category-container" style="clear:both;" id="ul-attribute137-69">
<img onclick="listSwitcher();" src="" id="a137-32" class="swatch-category" alt="Beige" width="12px" height="12px" title="Beige">
<img onclick="listSwitcher();" src="" id="a137-36" class="swatch-category" alt="Zwart" width="12px" height="12px" title="Zwart">
</div>
<p class="float-clearer"></p>
</div>
</div>
There are multiple popups on the site and thats what makes it difficult. At first I used this code
var link = jQuery('.photo').find('a')[0].getAttribute("href");
But this ofcourse only returns the href of the first popup. Then I tried this code:
var link = jQuery('.photo').closest('a').attr("href");
But this returned undefined
Then I tried this:
var link = jQuery(this).closest('a').attr("href");
But that also returns undefined
Edit
Here is the whole jQuery code snippet
jQuery(document).ready(function(){
jQuery('.swatch-category-container img').click(function(){
var kleur = jQuery(this).attr('title');
var link = jQuery('.photo').find('a').attr("href");
console.log(link);
link += "?kleur="+kleur;
console.log(link);
jQuery('.photo').find('.sendkleur').attr("href", link);
});
});
Working from the .swatch-category-container img element, you can traverse the DOM to find the required a like this:
$('.swatch-category-container img').click(function() {
var link = $(this).closest('.popup').find('.photo a').prop('href');
// do something with link here...
});
If this is the .swatch-category-container img element then, the anchor is the previous to previous sibling of the ancestor swatch-category-container element
var link = jQuery(this).closest('.swatch-category-container').prev().prev().attr("href");
Since you said multiple popups, the idea would be like this.
1. Get all popups
2. From each popup in all popups
Get the photo href item
$('.popup').each(function() {
var hrefItem = $(this).find('.photo a').attr('href');
//Do your processing with href item
});

image gallery pop-up swipes to every other image

I have built my first jQuery mobile image gallery, but I have a bug I can't seem to fix. When an image is tapped it pops up to full screen and to carousel all the images I can swipe the images or tap prev/next arrows.
Edit: The problem has changed slightly since I wrote this question, therefor I need to make a few changes in my question and my code.
The images now swipe to every other image, according to the order they are shown in the gallery. I'm dynamically adding a data-index to each image, but somehow the result is tabindex="0" for each image that pops up.
<body>
<!-- gallery content -->
<div data-role="content" id="pagecontent" class="gallerycontent">
<a href="#imgshow" data-transition="pop" data-rel="dialog">
<img src="../img/someimage.jpg" alt="someimage.jpg"/>
</a>
<!-- plus more unordered images -->
</div> <!--/content-->
</div><!-- /page -->
<!-- full screen image preview -->
<div data-role="dialog" id="imgshow" data-theme="d">
<div data-role="header" data-theme="d">
<div id="dialoghead"></div>
</div>
<div data-role="content" data-theme="d">
<center><div id="dialogcontent"></div></center>
</div>
<div data-role="footer">
<center>
Previous
Next
</center>
</div>
</div>
</body>
The 'on-touch' function and 'gonext' function in jquery.
//on-touch function
$('.gallerycontent img').bind('tap',function(event, ui){
var src = $(this).attr("src");
var alt = $(this).attr("alt");
$('#dialogcontent').empty().append('<img src="' + src + '" style="width:100%;"/>' );
$('#dialoghead').empty().append('<center><h2>' + alt + '</h2></center>' );
$(this).parent().addClass('selectedimg');
});
function gonext() {
var current = $('a.selectedimg');
if (current.hasClass('last')) {
var next = $('a.first')
} else {
var next = current.next();
}
var src = next.find('img').attr("src");
var alt = next.find('img').attr("alt");
next.addClass('selectedimg');
current.removeClass('selectedimg');
$('#dialogcontent').empty().append('<img src="' + src + '" style="width:100%;"/>' );
$('#dialoghead').empty().append('<center><h2>' + alt + '</h2></center>' );
}
Any thought or hints?
I think the problem might be that the selectedimg class isn't being removed when the popup is opened. Try adding this line
$('.selectedimg').removeClass('selectedimg');
just before the addClass line into this function, like this:
//on-touch function
$('.gallerycontent img').bind('tap',function(event, ui){
var src = $(this).attr("src");
var alt = $(this).attr("alt");
$('#dialogcontent').empty().append('<img src="' + src + '" style="width:100%;"/>' );
$('#dialoghead').empty().append('<center><h2>' + alt + '</h2></center>' );
$('.selectedimg').removeClass('selectedimg');
$(this).parent().addClass('selectedimg');
});

Categories