1

Lo que tengo que hacer, es que dentro de un recuadro que aparece en el lado inferior izquierdo, cuando toque el carrito, se abra un cuadrado blanco. Eso lo tengo, pero cuando tengo que mostrar los productos que estan en el array carritos, los productos del array, no aparece. Mi HTML es:

        class Producto {
constructor(id, descripcion) {
    this.id = id;
    this.descripcion = descripcion;
}
}
let productos = [];
let carritos = [];

productos.push(new Producto("751100", "Manija"));
productos.push(new Producto("851100", "Manija"));
productos.push(new Producto("751200", "Manija"));
productos.push(new Producto("753100", "Manija"));

let section = document.querySelector('.tiendaOnline.row.separar.container-fluid');

for (const producto of productos) {
let article = document.createElement("article");
article.className = "col col-12 col-md-6 col-lg-4 carta";
article.innerHTML = `   <img src="../imagenes/ft-nosotros.jpg" class="img-fluid" alt="Imagen de Producto">
                        <div>
                        
                        <h3 class="codigo">${producto.id}</h3>
                        <p class="descripcion">${producto.descripcion}</p>
                        <p>Precio</p>

                            <div>
                                <div class="btnCompra">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                            class="bi bi-cart" viewBox="0 0 16 16">
                            <path
                                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                        </svg>
                                <a href="" id="${producto.id}">Agregar al Carrito</a>
                                </div>
                                <a href="" id="detalles${producto.id}" class="btnDetalles">Ver detalles</a>
                            </div>
                        </div>`;
// Agregar a sección y no al documento
section.appendChild(article);

let articleProducto = document.getElementById(producto.id);
articleProducto.onclick = function (event) {
    event.preventDefault();
    carritos.push(event.target.id);
}
console.log(carritos);


}

let svgCart = document.getElementById('svgCart');
svgCart.onclick = () =>{
let section = document.getElementById('carrito');
if(section.classList.contains('noShow')){
    section.classList.remove('noShow');
    section.classList.add('show');
}else{
    section.classList.remove('show');
    section.classList.add('noShow');
}
}

let carritoMostrar = document.getElementById('carrito');
for(const index of carritos){
let article = document.createElement('article');
}

let sectionCarrito = document.getElementById('carrito');

for(const carrito of carritos){
    let article = document.createElement('article');
    article.className='col col-sm-12 col-md-12 col-lg-12 col-xl-12'
    article.innerHTML=` <div class="divCarrito">
                            <img src="" alt="" class="imgCarrito col col-md-6 col-lg-6 col-6">
    
                                <div class="col col-md-6 col-lg-6 col-6">
                                    <h5>${carrito}</h5>
                                </div>
                        </div>`

    sectionCarrito.appendChild(article);
}
    .tiendaOnline {
margin-top: 50px;
display: flex;
justify-content: space-around;

.carta {
  width: 425px;
  height: 438px;
  background-color: white;
  color: #646363;
  border-color: #000 3px solid;
  border-radius: 20px;
  /* The slow way */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
  transition: box-shadow 0.3s ease-in-out;
  margin-top: 20px;

  &:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  }

  img {
    width: 423px;
    height: 217px;
    margin-top: 5px;
    border-radius: 20px;
  }

  div {
    h3.codigo {
      margin-top: 15px;
    }

    div {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .btnCompra {
        background-color: #bada55;
        border-radius: 20px;
        height: 35px;
        width: 50%;
        padding: 5px;
        text-align: center;
        transition: box-shadow 0.3s ease-in-out;

        &:hover {
          box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
          -webkit-box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
          -moz-box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
        }
      }


      .btnDetalles {
        width: 30%;
        color: #646363;
      }
    }

  }
}
  }
  .svgCart {

  position: fixed;
  top: 90%;
  right: 1%;
  z-index: 5;
  border: 2px solid #bada55;
  border-radius: 20px;
  width: 50px;
  height: 50px;
  padding: 5px;
  cursor: pointer;
  transition: all 1 ease-in-out;

  &:hover {
background-color: #BADA55;
cursor: pointer;
  }
}

#carrito.show {
  position: fixed;
  top: 70%;
  right: 1%;
  width: 30%;
  border-radius: 10px;
  background-color: #fff;
  height: 20vh;
  border: 2px solid black;
  overflow-y: auto;
}

#carrito.noShow {
  display: none;
}

article {
  .divCarrito {
border: 2px solid black;
transition: box-shadow 0.3s ease-in-out;
z-index: 6;

&:hover {
  box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
  -webkit-box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
  -moz-box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
}
  }
}
    <section class="tiendaOnline row separar container-fluid">


        <article class="col col-12 col-md-6 col-lg-4 carta">
            <img src="../imagenes/ft-nosotros.jpg" class="img-fluid" alt="Imagen de Producto">
            <div>
                <h3>Lorem, ipsum.</h3>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
                <p>Precio</p>
                <div>
                    <div class="btnCompra">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                            class="bi bi-cart" viewBox="0 0 16 16">
                            <path
                                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                        </svg>
                        <a href="">Agregar al Carrito</a>
                    </div>
                    <a href="" class="btnDetalles">Ver detalles</a>
                </div>
            </div>

        </article>



    </section>
    <svg xmlns="http://www.w3.org/2000/svg" width="42" height="42" fill="currentColor" id="svgCart" class="bi bi-cart svgCart"
                viewBox="0 0 16 16">
                <path
                    d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
    </svg>
    <section id="carrito" class="noShow">
        
    </section>

Pero no funciona, cuando yo abro section.Tiene un toggle() que lo que hace es con un icono abrir o cerrar ese section, para que se vea o se oculte. No sé si tiene algo que ver que tenga una position:fixed

Muchas Gracias!

1

1 respuesta 1

2

No es que no se pueda agregar HTML al contenedor, sino el momento en que quieres hacerlo. Tienes esto:

let articleProducto = document.getElementById(producto.id);
articleProducto.onclick = function (event) {
    event.preventDefault();
    carritos.push(event.target.id);
}
console.log(carritos);

se supone que se van a agregar productos hasta que se haga clic en cada enlace, sin embargo, más adelante intentas crear el HTML en cuanto se carga la página, cuando carritos todavía está vacío; mientras que esta función solo agrega el producto a un arreglo, sin generar HTML.

Te propongo algunos cambios:

  • Para empezar, en el enlace guarda ID del producto como atributo de datos (dataset) y una clase para poder identificar (siguiente punto)
  • Escucha los clics en el contenedor de productos y analiza si fue en el enlace para agregar (elemento con clase btn-add)
  • Si el clic fue en el botón, entonces obtienes ID y accedes al contenedor padre (.closest('article')) y buscas la descripción por clase del elemento (.querySelector('.descripcion')) y contenido de texto
  • Con esos datos, ya puedes actualizar el arreglo carritos (que deberías guardar en localStorage o cookie) y agregas el HTML correspondiente al producto

class Producto {
constructor(id, descripcion) {
    this.id = id;
    this.descripcion = descripcion;
}
}
let productos = [];
let carritos = [];

productos.push(new Producto("751100", "Manija"));
productos.push(new Producto("851100", "Manija"));
productos.push(new Producto("751200", "Manija"));
productos.push(new Producto("753100", "Manija"));

let section = document.querySelector('.tiendaOnline.row.separar.container-fluid');

for (const producto of productos) {
let article = document.createElement("article");
article.className = "col col-12 col-md-6 col-lg-4 carta";
article.innerHTML = `   <img src="../imagenes/ft-nosotros.jpg" class="img-fluid" alt="Imagen de Producto">
                        <div>
                        
                        <h3 class="codigo">${producto.id}</h3>
                        <p class="descripcion">${producto.descripcion}</p>
                        <p>Precio</p>

                            <div>
                                <div class="btnCompra">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                            class="bi bi-cart" viewBox="0 0 16 16">
                            <path
                                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                        </svg>
                                <a href="" data-id="${producto.id}" class="btn-add">Agregar al Carrito</a>
                                </div>
                                <a href="" id="detalles${producto.id}" class="btnDetalles">Ver detalles</a>
                            </div>
                        </div>`;
    // Agregar a sección y no al documento
    section.appendChild(article);
}

let svgCart = document.getElementById('svgCart');
svgCart.onclick = () => {
    let section = document.getElementById('carrito');
    if(section.classList.contains('noShow')) {
        section.classList.remove('noShow');
        section.classList.add('show');
    } else {
        section.classList.remove('show');
        section.classList.add('noShow');
    }
}

// Escuchar clics en listado de productos
section.addEventListener('click', e => {
    // Solo si el clic fue en botón para agregar producto
    if(e.target.classList.contains('btn-add')) {
        // Cancelar evento del enlace
        e.preventDefault();
        let sectionCarrito = document.getElementById('carrito');
        // Tomar ID desde atributo de datos
        let productId = e.target.dataset.id;
        // Obtener descripción, buscando primero el padre y luego el elemento por clase
        let descrip = e.target.closest('article').querySelector('.descripcion').textContent;
        // Insertar en arreglo, deberías guardarlo en algún lado, localStorage o cookie
        carritos.push(productId);
        // Agregar HTML al carrito
        let article = document.createElement('article');
        article.className='col col-sm-12 col-md-12 col-lg-12 col-xl-12'
        article.innerHTML=` <div class="divCarrito">
                            <img src="" alt="" class="imgCarrito col col-md-6 col-lg-6 col-6">
    
                                <div class="col col-md-6 col-lg-6 col-6">
                                    <h5>${productId} - ${descrip}</h5>
                                </div>
                        </div>`
        sectionCarrito.appendChild(article);
    }
});
.tiendaOnline {
margin-top: 50px;
display: flex;
justify-content: space-around;

.carta {
  width: 425px;
  height: 438px;
  background-color: white;
  color: #646363;
  border-color: #000 3px solid;
  border-radius: 20px;
  /* The slow way */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
  transition: box-shadow 0.3s ease-in-out;
  margin-top: 20px;

  &:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  }

  img {
    width: 423px;
    height: 217px;
    margin-top: 5px;
    border-radius: 20px;
  }

  div {
    h3.codigo {
      margin-top: 15px;
    }

    div {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .btnCompra {
        background-color: #bada55;
        border-radius: 20px;
        height: 35px;
        width: 50%;
        padding: 5px;
        text-align: center;
        transition: box-shadow 0.3s ease-in-out;

        &:hover {
          box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
          -webkit-box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
          -moz-box-shadow: 4px 4px 13px -2px rgba(79, 79, 79, 0.76);
        }
      }


      .btnDetalles {
        width: 30%;
        color: #646363;
      }
    }

  }
}
  }
  .svgCart {

  position: fixed;
  top: 90%;
  right: 1%;
  z-index: 5;
  border: 2px solid #bada55;
  border-radius: 20px;
  width: 50px;
  height: 50px;
  padding: 5px;
  cursor: pointer;
  transition: all 1 ease-in-out;

  &:hover {
background-color: #BADA55;
cursor: pointer;
  }
}

#carrito.show {
  position: fixed;
  top: 70%;
  right: 1%;
  width: 30%;
  border-radius: 10px;
  background-color: #fff;
  height: 20vh;
  border: 2px solid black;
  overflow-y: auto;
}

#carrito.noShow {
  display: none;
}

article {
  .divCarrito {
border: 2px solid black;
transition: box-shadow 0.3s ease-in-out;
z-index: 6;

&:hover {
  box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
  -webkit-box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
  -moz-box-shadow: 10px 10px 37px -15px rgba(0, 0, 0, 0.73);
}
  }
}
<section class="tiendaOnline row separar container-fluid">

        <!-- Todo esto no es necesario, no es un producto real ****
        <article class="col col-12 col-md-6 col-lg-4 carta">
            <img src="../imagenes/ft-nosotros.jpg" class="img-fluid" alt="Imagen de Producto">
            <div>
                <h3>Lorem, ipsum.</h3>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
                <p>Precio</p>
                <div>
                    <div class="btnCompra">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                            class="bi bi-cart" viewBox="0 0 16 16">
                            <path
                                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                        </svg>
                        <a href="">Agregar al Carrito</a>
                    </div>
                    <a href="" class="btnDetalles">Ver detalles</a>
                </div>
            </div>

        </article>
        ***** Fin de HTML que no es necesario -->


    </section>
    <svg xmlns="http://www.w3.org/2000/svg" width="42" height="42" fill="currentColor" id="svgCart" class="bi bi-cart svgCart"
                viewBox="0 0 16 16">
                <path
                    d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
    </svg>
    <section id="carrito" class="noShow">
        
    </section>

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.