What is the best way to assign src and alt attributes to an image tag using JavaScript?

As I continue to learn JavaScript, please bear with me as I navigate through my current level of understanding. I am working on a gallery that opens a modal when an image is clicked. I have successfully gathered all the image sources into an array and used forEach to append them within li and img tags in a parent ul element, setting the sources as the src attribute.

However, I'm facing an issue with also needing to set alt attributes for each image from a separate array. Trying to accomplish this within the same forEach loop seems cluttered, and using another loop for alt attributes doesn't feel efficient. Perhaps there's a simpler solution that I haven't grasped yet.

I'm sharing the existing code below. Would it be better to consider using a JSON object instead of the current method?

 $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i++) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);
            
            function imageFunction(item){
               $('.image-modal ul').append('<li class="image-modal-item"><img class="modal-content" alt="" src="' + item + '" /><p id="aurora-gallery-image-title"></p></li>');
            }
           
      }); 

Answer №1

forEach() function includes the array index as a second parameter in the callback function. This can be utilized to retrieve the corresponding element from the imageTitles array.

function displayImage(item, index){
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${imageTitles[i]}" src="${item}" /><p id="aurora-gallery-image-title">  </p></li>`);
}

However, it is possible to achieve this without the use of arrays. Simply implement it within a for loop:

for (let i = 0; i < images.length; i++) {
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${images[i].alt}" src="${images[i].src}" /><p id="aurora-gallery-image-title">  </p></li>`);
}

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

An unanticipated error occurred at **** Unauthorized access when attempting to read **** location

I encountered an error message saying: "Unhandled exception at 0x00d23737 in Test.exe: 0xC0000005: Access violation reading location 0x8a8c0344" This issue arises when running the code snippet below: int main(int argc, char* argv[]) { string My_String_Arr ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

When the mouse button is released or when an event listener is

I've been pondering a question that has yet to be fully answered. When I implement this technique to catch a mouse up event: <div onmouseup="/*Script to be executed*/"></div> Is it more efficient than this newer approach: <div id=" ...

Having trouble with the automatic closing feature of Bootstrap drop down in React?

While using the drop button feature of Bootstrap, I have encountered a situation where it works fine when clicked on, but disabling it by clicking outside using autoClose='outside' does not seem to work as expected. When I click on my hamburge ...

What steps should I take to resolve the 'Uncaught Error: Cannot find module 'path'' issue in my React.js application?

While developing a web application in react.js, I encountered errors that I couldn't solve despite trying various solutions found online. The console displays the following error: Error in Console: Uncaught Error: Cannot find module 'path' ...

Having trouble accessing state within setInterval in React.js

My attempts to access the state of a component within a setInterval are not yielding the desired results. Here is the code snippet that is not working as expected: componentDidMount: function() { setInterval(function() { console.log(this.state); ...

I aim to combine a few variables of uncertain types within a string

When using concatenation with pluses, it could potentially result in unexpected outcomes. My desired result is 123. var one = 1; var two = 2; var three = '3'; var result = one + two + three; alert(result);//I want-> 123 ...

Having trouble retrieving a variable by POST in the backend through AJAX, yet it works perfectly fine in the frontend

Hey there! I'm facing an issue that I'm hoping someone can help me with. I'm attempting to send a tag attribute, stored in a JavaScript variable, to the backend (PHP) via AJAX. $.ajax({ type: "POST", url: '/requests/mercury.php ...

JavaScript failed to execute

I am trying to make the JavaScript function execute when the subcat-tab class is clicked, but for some reason it's not working. There are no error messages showing up, but nothing is happening. This is within a phtml file in Magento 2. <a href=&qu ...

How to Show Extensive Content in an Android WebView with a Fixed Height

Is anyone familiar with how to make a large HTML page fit completely within a web-view on an Android device without any vertical scroll bars? I want the entire webpage to be displayed within the varying height of the web-view when the user clicks "fill hei ...

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...

How can I alter the center point of an Object3D in Three.js?

I have a scenario where I am adding meshes dynamically to an Object3D. I'm curious if there is a way to obtain the center of the object so that I can apply rotations and translations evenly across the entire mesh, rather than having them centered on o ...

Display all event date markers, even if some dates are missing

Using the FullCalendar plugin has been a great experience for me. I have managed to successfully read data from a JSON object with the following code: function press1() { var employees = { events: [] }; ...

Efficiently Measuring the Visibility Area of DetailsList in Fluent UI

I am currently utilizing the DetalisList component alongside the ScrollablePane to ensure that the header remains fixed while allowing the rows to scroll. However, I have encountered a challenge as I need to manually specify the height of the scrollable co ...

Issues arose when attempting to navigate in a JavaScript handler within ASP.NET MVC

As a newcomer to Javascript, I hope my question isn't too basic. I have a button in my ASP.NET MVC 4 view: <input name="button" type="button" id="button1" value="Click me1"/> In order to create a click handler for the button, I've added ...

Assign value to a document field in MongoDB only if the field does not already exist

I am trying to update a field in a MongoDB document only if it does not already exist. However, my code doesn't seem to be working. Can somebody please point out what is wrong with it? await UserAnalytics.findOneAndUpdate( { user }, { ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

Set up local package dependencies using npm

My current situation involves having an npm dependency installed from a local path, which also has its own dependencies. I have observed that in this scenario, npm simply copies the contents of the local folder into node_modules. Is there any possible wa ...

How can you manipulate and refine JSON data with Typescript Angular?

Here is a string I'm working with: configValues="{listValues:[{name:chennai,attrs:[{id:1,name:kumar},{id:2,name:john}]},{name:bengalur,attrs:[{id:1,name:raj},{id:2,name:nick}]}]}" This string contains a list of values based on city. I am tr ...

transforming numbers to text using ajax

Below is the AJAX code I am using to update passwords in my database table: $.ajax({ type: 'POST', url: root_url + '/services/services.php?method=updatesubpwd', data: { 'sid': ptcid, 'pwd&ap ...