What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs.

<script type="text/javascript>
        function showFeed(data, contentId){
            var element = document.getElementById(contentId);
            if(data.status == 'ok'){    
                var feedLength = data.items.length;
                var output = '';
                for(var i=0;i<1;++i){
                    output += '<p><a href="' +
                    data.items[i].link + '" target="_blank" >' +
                    data.items[i].title + '</a>';
                }
                element.innerHTML = output;
            }
        }

        // Loop through multiple feeds
        var feedsInfo = [
             {id: 'cpa', url: 'http://feedurlplaceholder1'},
             {id: 'fs', url: 'http://feedurlplaceholder2'},
             {id: 'wealth', url: 'http://feedurlplaceholder3'}
        ];

        feedsInfo.forEach(function(feed, index) {
            var scriptElement = document.createElement('script');
            scriptElement.src = "http://rss2json.com/api.json?callback=showFeed"+ (index+1) +"&rss_url="+ encodeURI(feed.url);
            document.body.appendChild(scriptElement);
        });
        
</script>

Answer №1

Include a new argument in the function to handle the specific element.

Answer №2

Here is an example:

<script>
function displayData(id, content) {
    var element = document.getElementById(id);
    if(content.status == 'success'){    
        var length = content.items.length;
        var output = '';
        for(var i = 0; i < length; ++i){
            output += '<p> <a href="' +
            content.items[i].link + '" target="_blank" >' +
            content.items[i].title + '</a>';
        }
        element.innerHTML = output;
    }
}

displayData("cpa", cpaData);
displayData("fs", fsData);
displayData("wealth", wealthData);
</script>

Answer №3

Glad to see you doing well!

I want to share a handy function called showFeed() which takes two parameters: data and varFlag. Here's how it works:

<script type="text/javascript">
     function showFeed(data, varFlag){
         if(data.status == 'ok'){    
             var feedLength = data.items.length;

             var output = '';
             for(var i=0;i<1;++i){
                 output += '<p><a href="';
                 output += data.items[i].link + '" target="_blank" >';
                 output += data.items[i].title + '</a>';
             }

             if(varFlag === 'cpa') { cpaContent.innerHTML = output; }

             if(varFlag === 'fs') { fsContent.innerHTML = output; }

             if(varFlag === 'wealth') { wealthContent.innerHTML = output; }
         }
     }

     var cpaContent = document.getElementById('cpa');
     showFeed(data, 'cpa');

     var fsContent = document.getElementById('fs');
     showFeed(data, 'fs');

     var wealthContent = document.getElementById('wealth');     
     showFeed(data, 'wealth');    
</script>

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

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Issues with deploying Flask application on Google Cloud Platform's App Engine

Attempting to deploy a Flask application on Google App Engine (GAE) using Windows has proven to be a challenging task. While the app runs smoothly locally, encountering issues when attempting to run it on GAE. The first hurdle arises in flask\json.py ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

Custom HTML select element not triggering the onchange event

I found a code snippet on https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select that demonstrates a custom select input with an onchange event. However, I am facing an issue where the onchange event does not get triggered when I change th ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

I am experiencing an issue where a JSON string array is being converted into a C# List object, but each field of a Model inside the List is returning a "null

I have a string that contains JSON array data, and I'm attempting to convert it into a List of C# Model objects. Although the line of code I'm using shows the correct count with "objectList.Count," when I inspect the list during debugging, every ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

Transforming the text color after clicking on it on Squarespace - here's how to do it!

How can I make text change color upon clicking in Squarespace? Where should I place the block id in the code to target a specific block? Check out the code snippet I've been experimenting with: <script> document.getElementById('chang ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Encountering a java heap space exception while attempting to process massive JSON data with Spring RestTemplate

Currently, I am utilizing Resttemplate to consume a large JSON from an external server. The code functions as expected with smaller datasets; however, when tested against the full dataset, I encounter difficulties mapping the response to the bean class. Be ...

AngularJS allows for the creation of 2D arrays using the $Index

Currently, I am working on a project using AngularJS that involves creating a spreadsheet from a 2D array generated by the ng-repeat function. As part of this project, I am developing a function to update the initial values of the array when users input ne ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Solving required packages in Express server

I am encountering difficulties with resolving dependencies on my express server. Below is the structure of my project: Calculator --dist ----app -------calculator.js -------server.js --node_modules --src ----app --------calculator.js --------server.js -- ...

NgMap Angular Pins

While working on implementing Ng-Map for Angular in my application, I encountered an issue. I am retrieving entries from the database and attempting to drop markers on the map. However, even though I have 40 entries, only the first 11 are showing up as m ...