Tips for preventing the direct copying and pasting of JavaScript functions

Repeating the process of copying and pasting functions such as loadInitialValue(), loadInitialValue2(), loadInitialValue3(), is quite monotonous. This is the repetitive code snippet that I have been working on (when you click on "Mark as Read," the title of the short story fades to gray, otherwise it returns to white):

// Function for Short Story 1
function readunread() { 
    currentvalue = document.getElementById("readunread").value;
    if (currentvalue == "Mark as Unread") {
        document.getElementById("readunread").value = "Mark as Read";
        document.getElementsByClassName("read").value = "White";
        localStorage.setItem("readunread", "Mark as Read");
        localStorage.setItem("read", "White");
    } else {
        document.getElementById("readunread").value = "Mark as Unread";
        document.getElementsByClassName("read").value = "Gray";
        localStorage.setItem("readunread", "Mark as Unread");
        localStorage.setItem("read", "Gray");
    }
}

// Function for Short Story 2
function readunread2() { 
    currentvalue2 = document.getElementById("readunread2").value;
    if (currentvalue2 == "Mark as Unread") {
        document.getElementById("readunread2").value = "Mark as Read";
        document.getElementsByClassName("read2").value = "White";
        localStorage.setItem("readunread2", "Mark as Read");
        localStorage.setItem("read2", "White");  
    } else {
        document.getElementById("readunread2").value = "Mark as Unread";
        document.getElementsByClassName("read2").value = "Gray";
        localStorage.setItem("readunread2", "Mark as Unread");
        localStorage.setItem("read2", "Gray");
    }
}

// Function for Short Story 3
function readunread3() { 
    currentvalue3 = document.getElementById("readunread3").value;
    if (currentvalue3 == "Mark as Unread") {
        document.getElementById("readunread3").value = "Mark as Read";
        document.getElementsByClassName("read3").value = "White";
        localStorage.setItem("readunread3", "Mark as Read");
        localStorage.setItem("read3", "White");  
    } else {
        document.getElementById("readunread3").value = "Mark as Unread";
        document.getElementsByClassName("read3").value = "Gray";
        localStorage.setItem("readunread3", "Mark as Unread");
        localStorage.setItem("read3", "Gray");
    }
}

// Function to load initial value for Short Story 1
function loadInitialValue() {
    const localValue = localStorage.getItem("readunread");
    if (localValue == "Mark as Unread") {
        document.getElementById("readunread").value = "Mark as Unread";
    } else {
        document.getElementById("readunread").value = "Mark as Read";
    }
}

// More similar functions for other stories follow...

Is there a more dynamic approach to avoid repeating code for each short story? It would be cumbersome to create functions like "loadInitialValue100()" for 100 short stories. Is there a better way to handle this?

Answer №1

One way to streamline your code is by creating a generic function that can be reused with different parameters:

function toggleStatus(a) { // Example Function 
    const elemId = "status"+a;
    currentValue = document.getElementById(elemId).value;
    if (currentValue == "Mark as Inactive") {
        document.getElementById(elemId).value = "Mark as Active";
        document.getElementsByClassName("status"+a).value = "Green";
        localStorage.setItem(elemId, "Mark as Active");
        localStorage.setItem("status"+a, "Green");
    } else {
        document.getElementById(elemId).value = "Mark as Inactive";
        document.getElementsByClassName("status"+a).value = "Red";
        localStorage.setItem(elemId, "Mark as Inactive");
        localStorage.setItem("status"+a, "Red");
    }
}
// Instead of individual functions like toggleStatus1(), you can now call toggleStatus(1)

The same principle can be applied to other functions like initializeData().

If you have a large number of elements to work with, you can use a for loop like this:

for(let i = 1; i <= 100; i++)
{
   initializeData(i);
}

Answer №2

Another approach to tackle this:

function switchStatus(id, className, valueToCheck, color, condition) { 
    currentValue = document.getElementById(id).value;
    if (condition && currentValue == valueToCheck) {
        document.getElementById(id).value = valueToCheck;
        document.getElementsByClassName(className).value = color;
        localStorage.setItem(id, valueToCheck);
        localStorage.setItem(className, color);
        return;
    } 
    
    document.getElementById("statusSwitch").value = valueToCheck;
    document.getElementsByClassName("switch").value = color;
    localStorage.setItem("statusSwitch", valueToCheck);
    localStorage.setItem("switch", color);
}

// Handles if condition
switchStatus("statusSwitch", "switch", "Mark as Unread", "White", true);

// Handles else condition
switchStatus("statusSwitch", "switch", "Mark as Unread", "Grey", false);

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

What is the best way to handle a single promise from a shared listener?

I am working on implementing an event listener that will receive events from a server whenever a specific task is completed. I want to structure each task as a promise to create a more organized and clean workflow. How can I resolve each task promise by i ...

Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the . ...

Customize the position of nodes and their descendants in a d3 tree chart by setting specific x and y coordinates

I am in need of a d3 tree structure that looks like this. https://i.sstatic.net/X6U3u.png There are two key points to understand from the image above: Headers will have multiple parents(wells). I need to be able to drag and drop links connecting w ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...

Escaping quotes in JavaScript

After receiving a JSON object in the following format: result: { image: "..." title: "text text \"text\"" } I am currently utilizing underscore.js to render the template, but I am encountering an issue where the title displays with the escape ...

Using CSS GRID for creating layouts with customized grid-template-areas that include empty cells and automatic placement

Struggling with implementing the css grid layout module to showcase a 12-column, 3-row grid. The initial row should only contain two elements, positioned on each side of the grid with empty cells in between using ten periods. Subsequent rows should autom ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Converting an image to base64 format for storing in localStorage using Javascript

Currently, I am working on code that sets the background-image of a link. This is what I have so far: $("a.link").css("background-image", "url('images/icon.png')"); However, I want to enhance it by storing the image in localStorage: if (!local ...

Could you assist me in navigating the process of creating a dynamic 10x10 multiplication table using HTML and JavaScript? I'm eager to learn where to begin with this methodology

As I explore various questions related to the "simple" multiplication tables, I find myself with a more fundamental query. I am seeking clarity on how Javascript operates when intertwined with HTML, as that is where my confusion lies. In my multiplication ...

Preventing the reoccurrence of function events

I need to create an event triggered by a mouse click when the user clicks a button. The code snippet below shows my attempt, but I'm facing an issue where the function continues to run if the user clicks on a second input field after the initial one: ...

Is it possible to use the HTML script tag without specifying the type attribute as JavaScript? <script type="text/html"></script>?

While examining the source code of an HTML page, I stumbled upon the following snippet: <script id="searchItemTemplate" type="text/html"> <# var rows = Math.floor((Model.RecordsPerPage - 1) / 3 + 1); for (var i = 0; i < rows; ++i){ ...

Approach to CSS Layout: Creating Rounded Corners without CSS3 using images on all sides

I am faced with the challenge of creating a CSS layout that must adhere to specific minimum width and height requirements, yet expand to occupy 80% of the browser size. The main div I need to design should have rounded corners, utilizing images due to lack ...

Filling form fields with data from a dynamically created table using jQuery

I am facing an issue with populating the fields in the input box of my modal. The modal appears after clicking the Edit button in a table, and it should populate the fields based on the table row where the button is clicked. The table is generated using jQ ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

Issue caused by overflowing content and resizing the display

I am facing a challenge with my website. Essentially, my webpage has the <html> set to overflow:hidden, with two horizontal navbars, a fixed vertical sidebar on the left, and a central div with the height: 90% property. Edit: The container div now ...

"Get rid of the arrow in Bootstrap's dropdown menu

I'm currently using a bootstrap template that features an accordion menu. However, I have come across a scenario on one section of the page where I do not require the items to expand and show additional text, therefore, I would like to remove the arro ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

What is the best way to ensure that an ASync function only continues once all necessary information has been collected?

retrieveStudentGrades() { let grades = {}; let totalStudents = this.state.studentDetails.length; let studentCount = 0; this.state.courses.map((course) => { this.state.studentDetails.map((student) => { request.get( ...

Issues with NodeJS's "readline" module causing prompts not to be displayed

Recently, I decided to have some fun by creating a 'note' manager using NodeJS. However, I ran into an issue when trying to use readline.question() to prompt the user for their input on managing notes. The prompt was not being displayed as expect ...