Consolidate comparable JavaScript functions for increased efficiency

I've written this JS code, but I feel like there could be a better way to achieve the same results. Currently, I have 5 different functions that are quite similar, and I'm looking for a more efficient solution with less code repetition:

HTML:

<div class="news-wrap margin-top-div">
  <div class="news-btn-container-flex">
    <div class="news-btn-div current" data-tab="1" onclick="req(1)">1</div>
    <div class="news-btn-div" data-tab="2" onclick="req(2)">2</div>
    <div class="news-btn-div" data-tab="3" onclick="req(3)">3</div>
    <div class="news-btn-div" data-tab="4" onclick="req(4)">4</div>
    <div class="news-btn-div" data-tab="5" onclick="req(5)">5</div>       
  </div>

  <div class="news-content-container-flex">
    <div class="news-title">
      <span id="newsTitle">
      </span>
    </div>
    <div id="content-news">
    </div>
  </div>       

</div>

JS:

function req(num) {
  fetch(`https://jsonplaceholder.typicode.com/posts/${num}`)
    .then(function (res) {return res.json()})
    .then(function (json) {
      var title = json.title;
      var body = "";
      var i = 0;
      while (i <= 5) {
          body += json.body;
          i++;
      }
      document.getElementById("newsTitle").innerHTML = title;
      document.getElementById("content-news").innerHTML = body;
    });
}
req(1);
req(2);
req(3);
req(4);
req(5);

It seems like there is too much repetitive code in my current approach. I would like to streamline it while also ensuring compatibility with older browsers by avoiding using new features like ES6. Any suggestions on how I can improve this?

Answer №1

To append a value to a URL, you can create a function that takes an argument with the desired value and use this function in each click event. Here is an example:

function addValueToURL(id) {
  fetch('https://jsonplaceholder.typicode.com/posts/' + id)
    .then(function(res) {
      return res.json()
    })
    .then(function(json) {
      var title = json.title;
      var body = "";
      var i = 0;
      while (i <= 5) {
        body += json.body;
        i++;
      }
      document.getElementById("newsTitle").innerHTML = title;
      document.getElementById("content-news").innerHTML = body;
    });
}
addValueToURL(1);
<div class="news-wrap margin-top-div">
  <div class="news-btn-container-flex">
    <div class="news-btn-div current" data-tab="1" onclick="addValueToURL(1)">1</div>
    <div class="news-btn-div" data-tab="2" onclick="addValueToURL(2)">2</div>
    <div class="news-btn-div" data-tab="3" onclick="addValueToURL(3)">3</div>
    <div class="news-btn-div" data-tab="4" onclick="addValueToURL(4)">4</div>
    <div class="news-btn-div" data-tab="5" onclick="addValueToURL(5)">5</div>
  </div>

  <div class="news-content-container-flex">
    <div class="news-title">
      <span id="newsTitle">
      </span>
    </div>
    <div id="content-news">
    </div>
  </div>

</div>

Answer №2

To retrieve specific data, simply include the ID as a function argument.

function getData( id ) {
  fetch('https://jsonplaceholder.typicode.com/posts/' + id)
    .then(function (res) {return res.json()})
    .then(function (json) {
      var title = json.title;
      var body = "";
      var i = 0;
      while (i <= 5) {
          body += json.body;
          i++;
      }
      document.getElementById("newsTitle").innerHTML = title;
      document.getElementById("content-news").innerHTML = body;
    });
}

Implementation example:

getData( 5 );

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 array containing various types of data within a single structure

Is there a way to combine all the elements of this array into a single variable, rather than accessing them one by one as shown in the code snippet below? I want to store all the data within one variable without specifying an index for each element. Below ...

Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful! ...

Why does JSON.parse need to be run twice - once for a string and once for an object?

When I send a JSON string via websocket (Socket.io) from a Node.js server to a client's browser, I find that I have to execute the JSON.parse function twice in order to extract an object from the received JSON string. This behavior is confusing to me. ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

How to Store and Retrieve User-specific Data using Express and Mongoose?

Currently, I am developing a small single-page application that allows users to login using PassportJs and Mongoose. One of the main features I am working on is enabling users to log in and have a unique todo/task list associated with each user. I succes ...

Using a Firebase token repeatedly: simple steps to follow

I have integrated Firebase Web Notification using Firebase SDK. The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js To get access token, permission is requested by calling requestPermission function. Upon ...

Increase the dimensions of the jQuery modal confirmation box

I am working on a jQuery confirmation dialog that displays some details for the user. My goal is to have the dialog adjust its dimensions after the user clicks "YES" to show a smaller text like "Please wait...". How can I dynamically change the size of the ...

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

Node.js and node_modules operate in a streamlined manner to encode text within whatwg-url

While trying to execute a set of files, I encountered an error that keeps popping up. Interestingly, running a separate set of files loaded with a rest API on my localhost worked flawlessly without any errors. However, when switching back to the initial se ...

Transform your standard HTML buttons into a collective of radio buttons

Looking for a way to make some ordinary buttons function as radio buttons without adding another library to the project. Any suggestions on how this can be achieved using just HTML and JavaScript/jQuery? Appreciate any help, thank you. ...

The useLocation state is returning as null

I've encountered a debugging issue with my app. It's a straightforward application that fetches random API images from Spoonacular, allowing users to either select "Yah" or "Nah" similar to Tinder. Upon choosing "Yah", the image should be added t ...

Displaying file names underneath files in PHP

I am trying to create a PHP gallery that displays videos from a folder named "gallery." I want the name of each video to be displayed below the video itself on the page. I have attempted to combine code snippets from different websites, but so far, my atte ...

Pass along a variable with either "&" or "%" to a PHP file utilizing JavaScript

I have a JavaScript script that is sending 4 variables to a PHP page. The issue arises when one or more of these variables contain special characters like "&" or "%". The script ends up only sending the content before those characters. For example, if ...

Ways to determine if the property of a document has been altered?

Currently, I am in the process of writing tests for an Express CRUD application. The specific route I am focused on is the account recovery route. This route accepts POST requests with an email included in the body. Essentially, the application will search ...

What is the best way to refresh a grid in AngularJS every 5 seconds?

I am currently utilizing angular js and I would like to auto-refresh the grid every 5 seconds. Here is my angular js code for constructing the grid: App.controller('NGTableCtrl', NGTableCtrl); function NGTableCtrl($scope, $filter, ngTableParam ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Send HTML content to an Angular component for processing

I am looking to create a custom component called app-my-component, and I want it to be used in the following manner: <app-my-component> <div>Content goes here</div> </app-my-component> Furthermore, I would like to utilize this ...

Webpack is notorious for creating multiple copies of images

Having an issue with Webpack where it's generating duplicate images, one of which is broken. I have an original image image, and after running Webpack, two duplicates are created. One works fine: image, but the other one is broken: image. I'm us ...

Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected ima ...

Sort the array only for elements containing a specific key using Array.sort()

Let's consider an array like this: let arr = [ { label: "abc", value: 2, checked: true }, { label: "bcd", value: 1, checked: true }, { label: "cde", value: 4, checked: ...