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

Encountering a node-gyp error during the deployment of a Rails 6 application with a Vue app on Heroku

I'm running into an issue when trying to deploy my Rails 6 app with Vue on Heroku. The error I'm getting is as follows: [4/4] Building fresh packages... error /tmp/build_c242c7d78580af478535f5a344ff701e/node_modules/fibers: Command failed. ...

Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created: function addmovie_post() { { $genre = $this->post('genre'); $cast = $this->post('cast'); $director ...

How can you transform a variable into an HTML element using Angular?

Currently, I am working on parsing a JSON file that contains information about various articles. The structure of the JSON file is as follows: { "articles": [ { "id": 1, "title": "<h1>How to install Atom</h1>" }, { ...

The backend response was "<Response [502]>" along with an error message stating that string indices must be integers

Currently, my goal is to initiate a REST request towards the specified end-point. import requests param1 = "abc" param2 = "def" input_data = """{{"param1": {}, "param2": {}}}""".format ...

"Encountered an issue deserializing an object containing a List using Gson

I encountered this exception when trying to deserialize a JSON object using Gson: com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@588722d6 failed to deserialized json object [{"time":137 ...

Python's nested if conditions allow for more complex conditions to be

In a specific scenario, I am required to validate certain conditions within the provided JSON data and then take action accordingly. You can view the json data here. The condition that needs to be checked is as follows: Iterate through the JSON and ident ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

What could be causing my code to fail in the useEffect hook every time I make updates to my JSON

I have a function that receives JSON data from the server. Using the {jsonData.map((element) => renderComponents(element, jsonData))} function, I loop through the data and send each object to the renderComponents function along with the full JSON data. ...

Blur images on parent div when hovering using javascript

After some extensive searching, I came across a few helpful explanations on how to achieve my desired outcome. By combining them, I was able to get everything working smoothly with the hover effect over the image itself. However, when I attempted to trigge ...

Determining the Proper Data Type for Nested JSON in Flink's Elasticsearch Sink Using Python

I'm currently using Apache Flink and trying to send data to Elasticsearch with the built-in Elasticsearch Sink. I'm facing a challenge in setting the appropriate data type for the sink to accept my documents. The structure of my JSON documents i ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

The functionality of updating the logo in the browser tabs is not functioning as expected in Vue.js 3

This is the code from my index.html: <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE ...

Creating a JSON schema to organize regulations for internet inquiries

I am currently facing a challenge in structuring rules for web requests within a JSON object. Below are examples of the rules I need to store: Possible Conditions the user must be logged in the user must belong to an account of type [____] the user must ...

Issue with JSONP success function not being triggered

Here is an example of an Ajax call being made to a different domain: <script> $.ajax({ url: 'url?callback=?', dataType: 'jsonp', success: function (data) { alert(data[0].DeviceName) ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

Customizing the initial page layout in Elm

I am new to Elm and I need help with a particular issue. Can someone provide guidance or direct me to a useful resource for solving this problem? The challenge Iā€™m facing involves editing the start page of a website by removing specific elements, as list ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

I am having trouble converting my JSON formatted string into a JSON array using the SwiftyJSON library in Swift 3. Can anyone offer guidance on

I'm having trouble converting the following string received as a response from a server into a JSON array using Swift JSON in iOS. However, I can't seem to get it converted properly. Here is the string: [{\"Sno\":\"1\",&bs ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

Using PHP to set cookies after making an AJAX request

After reviewing numerous posts on this topic, I am still unable to set any cookies with my code. The initial ajax call in my code looks like this: $("#loginForm").submit(function(event) { event.preventDefault(); var uid = document.getElementById( ...