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

Exploring JSON parsing using javascript?

I'm currently attempting to work through this webRTC example and have encountered an issue that appears to be minor in nature... The if statement consistently fails to return true, despite the fact that the console message indicates that the property ...

ng-click-outside event triggers when clicking outside, including within child elements

I am looking to trigger a specific action when I click outside of the container. To achieve this, I have utilized the ng-click-outside directive which works well in most cases. However, there is one scenario where an issue arises. Inside the container, the ...

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

Retrieve checkbox selected value using pug and node.js

How can I retrieve the value of a checked checkbox in order to redirect to (href="/player/edit/:id") or (href="/player/delete/: id"), and obtain the player id for editing or deleting? I have omitted other code details such as app.js which includes the ser ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Setting the z-index to place an absolutely positioned element below a relatively positioned one

I am currently facing a challenge where I need to position an element under another one that has already been relatively positioned. The blue box must remain relatively positioned due to specific constraints within the website development process. For bet ...

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBacke ...

Converting a CSS Submenu from Horizontal to Vertical Orientation

Below is the current code snippet for my menu navigation bar: To access my live blog, please click on this link: www.4time2fun.com <div id="topmenu"> <div id="navigation"> <ul class="categories"> <li class="articles"> <a href ...

Express.js Res redirection problem occurring with Backbone.js due to failure in redirecting hashtag URLs

Issue Summary: Having trouble with Express.js redirect functionality. The problem occurs when trying to redirect after entering /#impulse, but works fine with /impulse/. Server processes the request for /#impulse before applying redirect checks, which re ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

Unable to extract a particular value from a JSON data structure

This situation has been on my mind for a good couple of hours now. I have this json object with example values like so: { "events": [ { "id": 64714, "live": false, "start": "1399117500", "league_ ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

What are some successful methods for displaying extensive data lists to users in a meaningful and organized manner?

From dropdown lists to hover menus with fly-out options, there are various ways to present content on a website... I am managing a comprehensive list of U.S. military bases across the world for my website. This list includes both active and inactive bases ...

Unable to retrieve file from server

Apologies for the basic question, but I'm feeling a bit lost at the moment. I've been diving into learning JavaScript and decided to set up a page on the 00webhost site to experiment and run tests. Everything was going well until I hit a roadblo ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

The Bootstrap tooltip effectively fades away after displaying text, but it is not positioned correctly above the icon

Having some issues with my tooltip functionality. It seems to display the text on the left side and fades away upon mouseover, but it doesn't show up in a proper tooltip box over the icon as expected. I suspect that there might be a conflict between j ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Elusive Appearance of the Flask Flash Message

I have developed a web application using Flask that allows users to upload files to an S3 storage. However, I would like to enhance the user experience by showing them the progress of their file uploads in real-time. To achieve this, I am utilizing Flash t ...