Tips for stopping variables from leaking in JavaScript

I'm currently working on a JavaScript code for my task manager website. Each page has its own JS file, but I've noticed that the data saved in one file seems to leak over to the others. How can I contain these variables so that tasks don't show up on unintended webpages?

Check out my website:


var myObj= { 
    textSelect: function(){
        document.getElementById('description').select();
    },
    
    hide: function() {
    document.getElementById("form").style.display = "none";
    document.getElementById("show").style.display = "inline-block";

},
    show:function(){

    document.getElementById("form").style.display = "block";
    document.getElementById("show").style.display = "none";
    document.getElementById('myDate').valueAsDate = new Date();
    },
    removeTask: function () {
    var id = this.getAttribute('id');
    var myTasks = returnToDo();
    myTasks.splice(id, 1);
    localStorage.setItem('myData', JSON.stringify(myTasks));
    document.getElementById('myTasks').innerHTML = '';
    showMyTasks();
    console.log('delete');

}
};
function returnToDo(){
    var myTasks = [];
    var myTasksTemp = localStorage.getItem('myData');
    if(myTasksTemp != null){
        myTasks = JSON.parse(myTasksTemp);
    }
    return myTasks;
}
function Task(){
    this.name = document.getElementById('name').value;
    this.subject = document.getElementById('subject').value;
    this.date = document.getElementById('myDate').value;
    this.describe = document.getElementById('description').value;
}
function newTask(x,y,z,o){
    document.getElementById('myTasks').innerHTML +=
        '<div class="col l3 m4 s12 animated zoomIn"> <h4>'+z+  ':</h1>'+
        '<p>'+y+'</p>' +
        '<p>By: '+x+'</p>' +
        '<p>Due: ' +o +'</p>'+
        '<div class="btn red" >Delete</div>'+
    '</div>'
}
function showMyTasks(){
    var myTasks = returnToDo();
    document.getElementById('myTasks').innerHTML = '';
    for(var i=0;i<myTasks.length;i++){
        newTask(
            myTasks[i].name,
            myTasks[i].describe,
            myTasks[i].subject,
            myTasks[i].date
        );
    }
    var button = document.getElementsByClassName('red');
    for (var j = 0; j < button.length; j++) {
        button[j].addEventListener('click', myObj.removeTask);
        console.log(button[j].addEventListener('click', myObj.removeTask));

    }
}
function submitInfo(){
    var myTasks = returnToDo();
    myTasks.push(new Task);
    localStorage.setItem('myData',JSON.stringify(myTasks));
    showMyTasks();
    myObj.hide();
}
showMyTasks();

Answer №1

Is there a way to prevent tasks from leaking over to another webpage?

When it comes to JavaScript programs within a <script> element, they are contained within the page where the element is located and do not carry over to other webpages.

I've noticed that saved data seems to leak into other JS files. How can this be avoided?

To prevent conflicts with variables declared in different <script> elements on the same page: Avoid using global variables.

You have a few options:

  1. Utilize
    <script type="module"
    to create your script as a module
  2. Enclose your script in a block and use const or let instead of var
  3. Wrap your code in an IIFE

It's also important to avoid implicit globals. Running your script in strict mode helps detect these errors more easily, and modules automatically run in strict mode.

Answer №2

To implement a TODO list across multiple pages, ensure the key used for saving data is unique to that specific list. You can achieve this by initializing a variable in your code and referencing it throughout your script.

<script>
  const todoPage = 'media';
</script>
<script src="yourTodoCode.js"></script>

When accessing local storage, utilize the variable you set:

// retrieve data
var myTasksTemp = localStorage.getItem(todoPage);
// save data
localStorage.setItem(todoPage, JSON.stringify(myTasks));

Consider creating a class to organize your code and reduce reliance on global variables.

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

Downloading multiple files concurrently in Flask

I am currently working on implementing a feature in Flask that allows users to download files from the client side. This feature should support downloading multiple files or just a single file. However, I am facing a challenge in providing the option to d ...

Having trouble retrieving data from mailosaur using protractor, even though it works fine with node.js

I've been trying to incorporate Protractor code with mailosaur for handling email functionality but I'm facing issues retrieving the value while coding in Protractor. Surprisingly, when I run the same code in node.js it works perfectly fine and I ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

Utilizing JQuery to ensure that rows have consistent height in two dynamically generated tables

To meet my specific requirements, I am tasked with creating two separate tables that will contain the same number of rows but different data. The first table will display Item Information, while the second table will provide consolidated information about ...

How can I enter a single backslash for location input in node.js without using double backslashes?

I have a project where the user needs to input a word to search for in files along with the folder location. However, I am struggling to write code that allows the user to input the location using single backslashes instead of double backslashes. const fol ...

Modify the text highlighted in bold within the AngularJS application

In my angular.js application, I have a table that displays elements. The name of these elements sometimes needs to be displayed in bold by adding <b> and </b> tags. However, instead of rendering the name as HTML code, it is showing up as a stri ...

What is the best way to include bootstrap using webpack?

I am currently building a webapp using Typescript and webpack. I have been able to successfully import some modules by including them in my webpack.config.js file as shown below. However, no matter how many times I attempt it, I cannot seem to import the b ...

What could be causing my click event to fail to register after sorting a WebGrid with a click?

Running into an issue with my webgrid and search button. It works perfectly if I search first, updating the grid with results. But when I click on a header to sort the grid, the search button stops working. Can't seem to figure out how to solve this d ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

Mastering Generic Types in Functions in Typescript

My current structure looks like this: export interface Complex { getId<T>(entity: T): string } const test: Complex = { getId<Number>(entity){return "1"} // encountering an error 'entity is implicitly any' } I am wondering w ...

The initial dropdown menu in PHP coupled with Javascript fails to retain my chosen option

As a novice PHP programmer, I successfully created a double drop-down list from a MySQL database. The idea is to choose a claims hub in the first box and then select an attorney associated with that specific hub in the second box. However, I am facing an ...

Transferring an object from one inventory to another

I'm in the process of developing a task manager that enables users to add and remove tasks. I am also working on enabling the ability for users to transfer tasks from one list to another. The current code I have written doesn't seem to be functio ...

AngularJS Expandable Table - Unlocking Limitless Possibilities

Take a look at the code snippet below: <tbody> <tr ng-repeat-start="ticket in tickets"> <td> <button ng-if="ticket.expanded" ng-click="ticket.expanded = false">-</button> <button ng-if="!t ...

Develop dynamic and stylized CSS using PHP within the Laravel framework

I am experiencing an issue with creating CSS files in Laravel within my controller. When I try to return the result, it shows up as a normal text file instead of a CSS file. In my routes.php file, I have: Route::get('/css/{css}.css', 'File ...

When the browser width is reduced, the text appears outside of the image

When pasting text into an image in this example, everything looks fine at first. However, as the browser width is reduced, the text starts slipping out of the picture. To make matters worse, unsightly line breaks are also added. Is there a way to prevent ...

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 ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

Utilizing hover effects and timeouts to conditionally show React components

I encountered a challenging React layout dilemma. It's not a complex issue, but rather difficult to articulate, so I made an effort to be as clear as possible. The data I have maps individual components in the following way: map => <TableRow na ...

Verify whether the session has been initiated and establish a global variable that can be utilized by JavaScript

I currently have the following arrangement: main.php page.php Whenever a user visits any of these pages, they experience an "introductory header animation". However, I want to ensure that this animation is only displayed on their initial visit and not w ...