Generating a download hyperlink using the image source attribute in jQuery

I have multiple galleries featuring images with captions. I'm striving to add a download link for each image at the end of its caption, based on the image source. However, I am facing an issue where the download icon is being appended to every image caption instead of just one 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>
        <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>
    </figure>

    <br />

    <figure class="gallery-item">
        <!-- BoGalleryImg -->
        <div class="gallery-icon landscape">
            <a href="http://creative.dev.j2noc.com/thehub/wp-content/uploads/2017/10/crkis-2379b.jpg" data-rel="lightbox-gallery-1"><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"></a>
        </div>
        <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>
    </figure>
</div>

jQuery

$(document).ready(function() {
    $('.attachment-full').each(function(index, element){
        var imgSrc = $(element).attr('src');
        console.log(imgSrc);  

        //Append Download Link to Caption
        $('.gallery-caption').append('<a href="'+imgSrc+'"  download><span class="glyphicon glyphicon-download-alt icon-download"></span></a>'); 
    }); 
});

I've been working on this problem for a couple of days now and I believe I'm close to solving it. If anyone has any suggestions on how to append only one download icon per corresponding image, I would greatly appreciate it.

Check out my CODEPEN DEMO

Answer №1

Your HTML code seems a little difficult to parse. Here is some jQuery code that can help you achieve your desired output with the 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'); 
})

https://i.sstatic.net/vatSQ.jpg

To use these icons, make sure to import Font Awesome:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

There might be other considerations for your gallery layout, but this should give you a good starting point for a cleaner approach.

If you face any issues with adding link attributes to your icons or need help with different layouts, feel free to reach out.

******** EDIT ********

If you prefer to stick with your original method, update your jQuery like 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 keep track of the image sources and download IDs, then use them accordingly at the end.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of jQuery mouseenter and mouseleave events seems to be malfunctioning when applied to newly injected DOM elements

I encountered an issue with my code. It functions properly, but when I introduce new elements into the dom, it fails to show or hide them. jQuery("div.cat-icon").on({ mouseenter: function () { jQuery(this).find('.catselect').show( ...

Explore further for additional information

I'm searching for a solution. Take this example in the pen ( codepen ), you'll find a read more and read less button set up. But how can I make this work with an HTML tag within the content? For instance, the 'more' class has the openi ...

Steps to create a thumbnail image following the insertion of an image into an input type="file" within a form, and subsequently submitting both elements on the form together

Currently, I am working on a form that enables users to upload images. Once the user submits the form, my goal is to create thumbnails for each image on the front-end and save them on the server afterwards. Due to security restrictions, changing the value ...

Decreased Performance in Vue Threejs with Larger JSON Data Sets

I am currently upgrading a legacy Three.js project from Angular 1.5 to Vue 2.6. The project is used for visualizing objects in JSON file format and I'm experiencing a drop in frame rate, going from ~60FPS in Angular to ~12FPS in Vue when loading large ...

Using an ajax call to dynamically generate an array for jquery autocomplete feature

Struggling to implement a jQuery UI autocomplete feature using data from a database via an AJAX call. Having difficulty figuring out how to pass the table of values to the autocomplete function. $( document ).ready(function() { $.ajax({ url ...

CSS: Styling different <a href> tags to appear uniform within identical size containers

I currently have some links displayed on my webpage. These links are encapsulated within a border and have a background set for them, essentially creating a box around each one. <!DOCTYPE html> <style> a { background: #DDD; border: #BB ...

Enhancing AngularJS routing with dynamic partial parameters

I have experience working with routes in different frameworks like Rails and Laravel, but I am now facing a challenge while working on an AngularJS site. In Laravel, we could dynamically create routes using foreach loops to handle different city routes. Ea ...

Updating a div with JQuery in Django with the utilization of the template engine

I am looking for a way to automatically refresh a div tag in Django that displays temperature data every 20 seconds. I have successfully achieved this by implementing the following functions: function autoRefresh() { $.ajax({ url: '{% url monitor-t ...

Submitting a form through AJAX, even when using the $(this) function for another form

Currently, I have a situation where there are two forms present on my page. The first form is located in the footer and serves as a contact page. The second form, named "product-form," is considered to be the main form. Within this form, PHP validation is ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

What causes the page to reload following a JavaScript post request?

Whenever I submit a post request containing JSON data to the server, the page gets refreshed after updating the username and score. Surprisingly, when I send a patch request, this issue does not occur and the page remains unchanged. I strongly desire that ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

performing a query on two tables with sequelize

There must be a more efficient way to accomplish this task with fewer lines of code. I am not very experienced with databases and I am new to sequelize and node. The user id is passed as a parameter and I need to check if there is a corresponding user in ...

Uploading a file to a server using HTML and PHP: a step-by-step guide

Looking to utilize PHP as a proxy for uploading files to a server. Any advice on how I can send the uploaded files along with a Basic Authorization header? ...

The new FormData(form) method unexpectedly returns an empty object

In this scenario, I am aiming to retrieve key-value pairs. The form on my page looks like this: <form id="myForm" name="myForm"> <label for="username">Enter name:</label> <input type="text" id="username" name="username"> ...

The navigation bar on the web app is functioning properly on Android devices but experiencing a CSS problem on

My Nextjs web app includes a navbar with a hamburger menu, logo, and avatar. The navbar functions perfectly on desktop in Chrome, Mozilla, Brave (in developer tools mobile mode), and on Android phones using Chrome. However, when accessed from an iPhone X, ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...

Reduce the size of the title background to be smaller than the width of the page

I am currently designing a website with a white background for the site title and tagline. However, I want the background of the site title to only cover the width of the actual title, rather than stretching 100% across the page. Any guidance on achieving ...

Mongoose: fetching values exclusively

I am currently utilizing Mongoose to query my User schema, which contains: var usersSchema = new Schema( { email : String, regId : { type : String , default : '' }, lastName : { type : String , default : '' ...