What is the best way to iterate through multiple arrays using a single for loop

I have various hidden popups that are triggered to show on click using some JavaScript magic. As a beginner in JavaScript, I find myself writing multiple lines of code that look very similar.

Currently, my code for handling these popup boxes looks like this:

var paperComButton = document.getElementsByClassName('paperCompanieButton');

for (var i = 0; i < paperComButton.length; i++) {
  paperComButton[i].addEventListener('click', function () {
    handlePopup('paperCompanieInfo');
  });
}

The next piece of code is almost identical:

var pdfPreviewButton = document.getElementsByClassName('pdfPreviewButton');

for (var i = 0; i < pdfPreviewButton.length; i++) {
  pdfPreviewButton[i].addEventListener('click', function () {
    handlePopup('paperJobPdf');
  });
}

The issue arises when dealing with more than just these two popups, resulting in lengthy JavaScript code.

My question: Is there a way to consolidate these code snippets into a more universal solution? I hope there's a straightforward approach that can help simplify the logic for my beginner understanding!

Answer №1

One of the reasons why Javascript utilizes functions is to streamline repetitive tasks by encapsulating them into reusable containers. In the given scenario, the similarities lie in the behavior of the buttons and the document ID. By creating a function that accepts these two variables as arguments, you can avoid redundant code. For instance, consider defining a function like:

function setPopup(className, documentID) {
    var buttons = document.getElementsByClassName(className);

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener('click', function () {

        var greyOut = document.getElementById('greyOut');
        var popupWrapper = document.getElementById('popupWrapperFlex');
        var popup = document.getElementById(documentID);

        greyOut.style.zIndex = '5';
        popupWrapper.style.zIndex = '6';
        popup.style.zIndex = '1';
        greyOut.style.opacity = '1';
        popupWrapper.style.opacity = '1';
        popup.style.opacity = '1';
        });
    }   
}

With this function in place, you can simply call it with different parameters to execute the same functionality without rewriting the entire block of code each time:

setPopup('paperCompanieButton', 'paperCompanieInfo')
setPopup('pdfPreviewButton', 'paperJobPdf')

This approach allows for flexibility in executing the desired actions multiple times.

Answer №2

To enhance the readability of this code, consider restructuring it as shown below:

function setupButtonsPopups(buttonClassName, popupId) {
    var buttons = document.getElementsByClassName(buttonClassName);
    var popup = document.getElementById(popupId);
    var greyOut = document.getElementById('greyOut');
    var popupWrapper = document.getElementById('popupWrapperFlex');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener('click', function() {
            greyOut.style.zIndex = '5';
            popupWrapper.style.zIndex = '6';
            popup.style.zIndex = '1';
            greyOut.style.opacity = '1';
            popupWrapper.style.opacity = '1';
            popup.style.opacity = '1';
        });
    }
}

setupButtonsPopups('paperCompanieButton', 'paperCompanieInfo');
setupButtonsPopups('pdfPreviewButton', 'paperJobPdf');

It is important to note that the only variation between these two blocks of code lies in the buttons class name and the popup id. Therefore, creating a function that accepts these arguments will streamline the code.

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

Transferring account information to a function call in the near-js-api

I am attempting to utilize the following method in near-js-api for my contract. It requires a Rust AccountId as input. What is the correct procedure to serialize an Account and send it to the contract? Also, are there any specific considerations when inv ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Does anyone know how to designate a Thumbnail when playing Audio on iOS Safari?

I recently launched a website to showcase my new podcast. The audio is embedded in a media player on the page, and when it's playing, it shows up on the Control Center audio tab and even on the lock screen. However, the thumbnail displayed is just a ...

Effortlessly choosing and setting values in jQuery Select2

This particular code is meant for versions of Select2 prior to version 4. Here is a simple select2 code snippet that retrieves data via AJAX. $("#programid").select2({ placeholder: "Select a Program", allowClear: true, minimumInp ...

Learn how to easily insert a marker on a map using leaflet js in vue 3 with just a simple click

Hey everyone! I need some help with a challenge I'm facing. I can't seem to get click coordinates to create a new Marker on my map. Check out the image here And another image here ...

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

What is the best way to pass an array of objects to a component as a prop and then distribute individual objects within the array as props to nested components?

Below this post, I delve into my desired goals and what has almost worked in my endeavors In my application, I have both the <oo-upload> and <oo-uploads> components defined. Essentially, <oo-uploads> showcases a table of <oo-upload> ...

Retrieving MAC Address from Client's Device

Question: How can I get the MAC and the IP address of a connected client in PHP? Can the MAC address of a client browsing my site be retrieved? Is it possible with JavaScript, jQuery, or PHP? I attempted to use JavaScript with the following code: a ...

Verify if input is selected using jQuery

Is it possible to achieve the following using jQuery? if($(this).parent().find('input:checked') == true) {$(this).find('.switch').attr('state','on');} else{$(this).find('.switch').attr('state',& ...

Best practice for dynamically adding/storing/creating HTML elements on the fly

What is the best approach to dynamically add and store HTML controls for dynamically added elements on an HTML page? Currently, I am developing a widget-based system where users can choose which widgets they want to display. They have the flexibility to s ...

Execute a task on the elements contained in an array within a collection of arrays

I'm grappling with a challenge that involves calculating the sum of the products of two elements that are housed in separate objects. Essentially, I'm seeking to determine TotalValue through the formula: TotalValue = Sum[Arrays.close * List.amtP ...

Tips for implementing resizable Material-UI Dialogs

I'm working on a project that involves creating a dialog box that can be resized and dragged. While I found steps in the Material-UI Dialog documentation on how to make it draggable, I'm still looking for information on how to make it resizable. ...

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...

Twice the charm, as the function `$("#id").ajaxStart(...)` is triggered twice within an AJAX request

I am trying to implement the following code: <script language="javascript"> function add(idautomobile,marque,model,couleur,type,puissance,GPS){ $("#notification").ajaxStart(function(){ $(this).empty().append("<center><br/><i ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

An issue arose upon scanning the QR code for whatsapp-web.js, indicating a potential

My WhatsApp web bot encountered issues this week. C:\pinkmeupwabot\node_modules\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:221 throw new Error('Eval ...

Exploiting jQuery UI in a Web Browser Bookmarklet

When using CoffeeScript, even though the code is very similar to JavaScript: tabs_html = "<div id='nm-container'><ul><li><a href='#tabs-1'>Guidelines</a></li><li><a href='#tabs-2'& ...

Is it possible to manually input data for a KendoScheduler DataSource through hard coding?

Currently, I am in the process of troubleshooting a KendoScheduler application, and my goal is to integrate some hard-coded data instead of relying on an ajax call. $("#scheduler").kendoScheduler({ dataSource: { transport: { ...

JavaScript, the art of escaping strings

I am dealing with the following string: 'You've just created' When I store this string in a JavaScript variable, it is seen as 2 separate strings due to the presence of a ' character. Is there a way to properly escape it? ...

What is the best way to retrieve AJAX post data from the request in Symfony2?

My goal is to efficiently upload a file using jquery-file-upload (blueimp) and include some data in a cross-domain environment. To achieve this, I have utilized code from the basic.html file provided by jqueryfileupload on the client side. Additionally, I ...