0

Recientemente he comenzado mi primer proyecto con JavaScript (mi primer lenguaje). Se trata de una aplicación de notas, donde al crear una nueva se crea un elemento que se agrega al DOM y al mismo tiempo al localStorage y lo contrario debería de pasar al eliminar la nota, pero mi problema está en la parte donde trato de borrar los datos de la nota que se encuentran en el localStorage.

¿Cómo puedo hacer esa función? He tratado de darle solución de varias formas. Una de esas soluciones da como resultado que borra todo menos la que quiero borrar, y no pude hacer nada para que pase lo contrario.

En otra me borra la nota que deseo pero me devuelve un montón de notas que contienen cada uno de los caracteres de la nota a eliminar, y las otras de plano no me sirven.

Nota: La última función es la que no puedo hacer.

Código:

const lista = document.getElementById('list');

function eventlisteners() {
    document.getElementById('btn-saved').addEventListener('click', agregarNotaDom);

    lista.addEventListener('click', borrarNotaDom);

    document.addEventListener('DOMContentLoaded', cargarData)
}
eventlisteners();

function agregarNotaDom() {
    let titulo = document.getElementById('title').value;
    let cuerpo = document.getElementById('body').value;
    // Contenedor de la nota
    let nota = document.createElement('div');
    nota.className = 'card bg-light mb-3';
    // Contenedor del header
    let header = document.createElement('div');
    header.className = 'card-header header-nota';
    // Titulo de la nota
    let tituloNota = document.createElement('p');
    tituloNota.textContent = titulo;
    // Boton borrar
    let btnDelete = document.createElement('button');
    btnDelete.className = 'borrar-nota';
    btnDelete.textContent = 'Borrar';
    // contenedor del body
    let bodyNota = document.createElement('div');
    bodyNota.className = 'card-body';
    // contenido nota
    let contenidoNota = document.createElement('p');
    contenidoNota.className = 'card-text';
    contenidoNota.textContent = cuerpo;
    
    lista.appendChild(nota);
    // HEADER
    nota.appendChild(header);
    header.appendChild(tituloNota);
    header.appendChild(btnDelete);
    // BODY
    nota.appendChild(bodyNota);
    bodyNota.appendChild(contenidoNota);

    guardarLocalStorage(titulo, cuerpo);
}
function borrarNotaDom(e, titulo, cuerpo){
    e.preventDefault();
    if(e.target.className === 'borrar-nota'){
        e.target.parentElement.parentElement.remove();
        console.log(e.target.parentElement.parentElement.remove())
    }
}
function guardarLocalStorage(titulo, cuerpo) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    titulos.push(titulo);
    cuerpos.push(cuerpo);

    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}
function obtenerNotasTitulosLocalStorage(){
    let titulos;
   
    if (localStorage.getItem('titulos') === null) {
        titulos = [];

    } else {
        titulos = JSON.parse(localStorage.getItem('titulos') ); 
    }
    return titulos;
}
function obtenerNotasCuerposLocalStorage(){
     let cuerpos;
     if (localStorage.getItem('titulos') === null) {

        cuerpos = [];
    } else {
        cuerpos = JSON.parse(localStorage.getItem('cuerpos') ); 
    }
    return cuerpos;
}
function cargarData(){
    let titulos = obtenerNotasTitulosLocalStorage();
    let cuerpos = obtenerNotasCuerposLocalStorage();

    for(let i = 0; i < titulos.length; i++){

        // Contenedor de la nota
        let nota = document.createElement('div');
        nota.className = 'card bg-light mb-3';
        // Contenedor del header
        let header = document.createElement('div');
        header.className = 'card-header header-nota';
        // Titulo de la nota
        let tituloNota = document.createElement('p');
        tituloNota.textContent = titulos[i];
        // Boton borrar
        let btnDelete = document.createElement('button');
        btnDelete.className = 'borrar-nota';
        btnDelete.textContent = 'Borrar';
        // contenedor del body
        let bodyNota = document.createElement('div');
        bodyNota.className = 'card-body';
        // contenido nota
        let contenidoNota = document.createElement('p');
        contenidoNota.className = 'card-text';
        contenidoNota.textContent = cuerpos[i];
        
        lista.appendChild(nota);
        // HEADER
        nota.appendChild(header);
        header.appendChild(tituloNota);
        header.appendChild(btnDelete);
        // BODY
        nota.appendChild(bodyNota);
        bodyNota.appendChild(contenidoNota);
    }
}
function borrarNotaLocalStorage(){
    
}
body{
    font-family: 'Raleway', sans-serif;
    margin-bottom: 50px;
}
.container{
    width: 100%;
    background-color: red;
}
.list{
    width: 90%;
    margin: 20% auto;
}
.bottomNav{
    background-color: #385b80;
    padding: 5px 10px;
    width: 90%;
    border-radius: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    bottom: 5px;
    left: 5%;
    position: fixed;
}
.btn-main{
    border-radius: 25px;
    width: 22%;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.btn-main > img{
    width: 65%;
}
/* MENU DESPLEGABLE */

.sub-menu{
    width: 90%;
    height: 400%;
    padding: 5px 0;
    position: absolute;
    bottom: 118%;
    left: 5%;
    border:2px solid #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    display: none;
    background-color: #d5d4d4;
    color: #3399F3;
}
.note{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    width: 100%;
    margin: 10px;
}
.title{
    margin-bottom: 0;
}
.note > .size-back{
    width: 80%;
    padding: 5px 5px;
    margin-bottom: 5px;
    border-radius: 5px;
    border:2px solid #ccc;
    color: rgb(116, 113, 113);
    text-align: center;
    font-size: 14px;
}
.note > textarea{
    height: 100px;;
}
.btn-saved{
    border: 1px solid gray;
    font-size: 14px;
    padding: 5px 15px;
}
.btn-saved:hover{
    color: white;
    background-color: #3399F3;
}
/* TRIANGLE */
span{
    color : #ccc;
    position: absolute;
    font-size: 36px;
    bottom: -18%;
    /* display: none; */
}

.btn-main:hover  > .sub-menu{
    display: flex;
}
/* elementos */

.header-nota{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.header-nota > p{
    margin-bottom: 0;
}
.borrar-nota{
    background-color: rgb(253, 47, 47);
    color: #fff;
    font-weight: 400;
    padding: 0.375rem 0.75rem;
    border: 0;
    border-radius: 0.25em;
}
.borrar-nota:focus{
    outline: none;
}
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>app</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    
    <link rel="stylesheet" href="css/fontello.css">
    <link rel="stylesheet" href="css/estilosPanel.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

    <style type="text/css">div.image {max-width: 256px;max-height: 256px;
    background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDUyIDUyIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1MiA1MjsiIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSIzMnB4IiBoZWlnaHQ9IjMycHgiPgo8Zz4KCTxwYXRoIGQ9Ik0yNiwwQzExLjY2NCwwLDAsMTEuNjYzLDAsMjZzMTEuNjY0LDI2LDI2LDI2czI2LTExLjY2MywyNi0yNlM0MC4zMzYsMCwyNiwweiBNMjYsNTBDMTIuNzY3LDUwLDIsMzkuMjMzLDIsMjYgICBTMTIuNzY3LDIsMjYsMnMyNCwxMC43NjcsMjQsMjRTMzkuMjMzLDUwLDI2LDUweiIgZmlsbD0iIzAwMDAwMCIvPgoJPHBhdGggZD0iTTM4LjUsMjVIMjdWMTRjMC0wLjU1My0wLjQ0OC0xLTEtMXMtMSwwLjQ0Ny0xLDF2MTFIMTMuNWMtMC41NTIsMC0xLDAuNDQ3LTEsMXMwLjQ0OCwxLDEsMUgyNXYxMmMwLDAuNTUzLDAuNDQ4LDEsMSwxICAgczEtMC40NDcsMS0xVjI3aDExLjVjMC41NTIsMCwxLTAuNDQ3LDEtMVMzOS4wNTIsMjUsMzguNSwyNXoiIGZpbGw9IiMwMDAwMDAiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K)}
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light navigator-title">
        <h1 class="navbar-brand  medio title">Lista de Tareas</h1>
        <button type="button" class="btn btn-secondary disabled bnt-back" onclick="location.href='index.html'">Cerrar</button>

    </nav>
    <div class="list" id="list">
        <!-- <div class="card bg-light mb-3" style="max-width: 20rem;">
                <div class="card-header">Header</div>
                <div class="card-body">
                  <h4 class="card-title">Light card title</h4>
                  <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                </div>
              </div> -->
      </div>
    <nav class="bottomNav">
        <button class="btn btn-primary btn-main" id="btnCreate" >
            <div class="sub-menu">
                <div class="titulo" class="size-back title"><p>Nueva nota</p></div>
                <div class="note">
                    <input type="text" id="title" class="size-back" placeholder="Dale un nombre a tu nota">
                    <textarea cols="30" rows="10" id="body" class="size-back" placeholder="Escribe tu nota aqui"></textarea>
                </div> 
                <div id="btn-saved" class="btn-saved">Crear nota</div>
                <span class="icon icon-down-dir"></span>
            </div> 
            <img src="data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgV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9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K" />
        </button>
    </nav>
    <script src="js/main.js"></script>
</body>
</html>

1 respuesta 1

1

En primer lugar y como tratas como operaciones atómicas las acciones de agregar y de borrar nota yo haría una función para cada una de ellas, donde internamente llames a las funciones que hacen cada una de las operaciones implicadas, es decir, partimos de:

function addNote() {
    addToDOM();
    addToLocalStorage();
}

function delNote() {
    delFromDOM();
    delFromLocalStorage();
}

con los argumentos que correspondan en cada caso.

Otra cosa, puedes ahorrar mucho código creando algunas funciones genéricas, por ejemplo:

function $(id) {
    return document.getElementById(id);
}

y para usarla:

let title = $('title').value;


En cuanto a tu problema: ¿Cómo borrar un dato del LocalStrorage?

Sí para almacenar un dato:

localStorage.setItem("name", "MiNombre");

para eliminar ese mismo dato:

localStorage.removeItem("name");


Para saber más sobre cómo funciona el almacenamiento en el navegador puedes visitar la página de MDN.


Editado

Para eliminar una nota concreta, partiendo de tu función:

function guardarLocalStorage(titulo, cuerpo) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    titulos.push(titulo);
    cuerpos.push(cuerpo);

    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}

puedes escribir una función que elimine la nota reescribiendo el almacenamiento después de haber eliminado la nota. Lo habitual sería trabajar con una ID para cada nota, en tu caso voy a suponer que el título de la nota es único, de no serlo usarias título y descripción para localizar la posición de la nota que vas a borrar.

function clearNoteFromLocalStorage(title) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    /**
     * Localizamos la posición de la nota a borrar
     *
     */
    let pos = titulos.indexOf(title);

    /**
     * Borramos la nota de los arrays (de titulos y de cuerpos)
     *
     */
    titulos.splice(pos, 1);
    cuerpos.splice(pos, 1);

    /**
     * Reescribimos el almacenamiento sin la nota en cuestion
     *
     */
    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}


Una vez todo funcione puedes optimizar código, por ejemplo:

function obtenerNotasCuerposLocalStorage(){
    let cuerpos;
    if (localStorage.getItem('titulos') === null) {
        cuerpos = [];
    } else {
        cuerpos = JSON.parse(localStorage.getItem('cuerpos')); 
    }
    return cuerpos;
}

puede ser reescrito como:

function obtenerNotasCuerposLocalStorage(){
    let cuerpos = [];
    if (localStorage.getItem('titulos') !== null) {
       cuerpos = JSON.parse(localStorage.getItem('cuerpos')); 
    }
    return cuerpos;
}
1
  • si se borrar un dato del localStorage, lo que no se es como decirle al programa cual debe de borrar exactamente el 23 dic. 2018 a las 17:00

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.