Home > Net >  How can I display only the newly added object in the array?
How can I display only the newly added object in the array?

Time:07-01

Help!, I've been racking my brain for hours but I still can't figure out what's wrong here.

Here's what I wanted to happen, every time I add a new book, it should display on the page, it does display. However, when I add in a new Book, the first Book I had added also shows up. I'm guessing it has something to do with the loop? How can I make it only display the newly added object in the array.

and if loop has nothing to do with it, why is it going like this? what is it that I am doing wrong?

//DOM Elements
        const modal = document.querySelector('.modal-container');
        const openModal = document.querySelector('.add-book-btn');
        const closeModal = document.querySelector('.modal-close-btn');
        const form = document.querySelector('.add-book-form');
        const bookGrid = document.querySelector('.book-grid');
        //open the add new book form
        openModal.addEventListener('click', () => {
            modal.classList.add('active');
        })
        //close the form
        closeModal.addEventListener('click', () => {
            modal.classList.remove('active');
        })

        //store book object in a simple array 
        let myLibrary = [];

        // object constructor
        function Book(title, author, pages, status) {
            this.title = title;
            this.author = author;
            this.pages = pages;
            this.status = status;
        }
      
        //function that can take user’s input and store the new book objects into an array. 
        function takeBookInfo() {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                let book = new Book(title.value, author.value, pages.value, status.value);
                //store the new object into an array.
                myLibrary.push(book);
                console.log(myLibrary);
                console.log(book);
                //hide modal as soon as the form is submitted
                modal.classList.remove('active');
                //reset form as soon as the form is submitted
                form.reset();
                //loop through existing and new Book object in the array
                addBookToLibrary();
               
            })
        }
        takeBookInfo();
        
        //function that loops through the array and displays each book on the page
        function addBookToLibrary() {
           for (let i = 0; i < myLibrary.length; i  ) {
              displayBook(myLibrary[i]);
           }
        }

        //displays each book on the page
        function displayBook(book) {
            const bookCard = document.createElement('div');
            bookCard.className = 'book-card';

            const bookTitle = document.createElement('p');
            bookTitle.className = 'book-title';
            bookTitle.textContent = book.title;
            bookCard.appendChild(bookTitle);

            const bookAuthor = document.createElement('p');
            bookAuthor.textContent = `by ${book.author}`;
            bookAuthor.className = 'book-author';
            bookCard.appendChild(bookAuthor);
            const bookPages = document.createElement('p');
            bookPages.className = 'book-pages';
            bookPages.textContent = `${book.pages} pages`;
            bookCard.appendChild(bookPages);

            bookGrid.appendChild(bookCard);
        }
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
}

:root {
    --header-color: #49361c;
    --content-color: #eeeadf;
    --box-shadow: 0 2px 4px 0 rgba(0,0,0,.2), 0 2px 3px 0 rgba(0,0,0,.2);
    --card-color: #fffbf7;
    --title-color: #362813;
    --button-color: #a58b63;
}

/* Header */
.header {
    min-height: 15vh;
    min-width: 100vw;
    box-shadow: var(--box-shadow);
    position: relative;
    z-index: 1;
}
.container {
    display: flex;
    background-color: var(--header-color);
    align-items: center;
    justify-content: space-between;
    padding: 0 40px;
}

.logo {
    min-height: 15vh;
    display: flex;
    align-items: center;
    gap: 25px;
    color: var(--content-color);
    text-shadow: 2px 2px 10px#362813;
}

.logo span {
    font-size: 6.5rem;
}

.title {
    font-family: 'Bilbo Swash Caps', cursive;
    font-size: 4rem;
    letter-spacing: 1.2rem;  
}

.add-book-btn {
    border: none;
    font-size: 3rem;
    border-radius: 50%;
    padding: 0 10px;
}

.add-book-btn:hover {
    cursor: pointer;
    background-color: #e0dede;
}



/* Main Content */
.main-container {
    min-height: 100vh;
    min-width: 100vw;
    background-color: var(--content-color);
    padding: 40px;
    z-index: 1;
}

.book-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(20vw, 1fr));
    gap: 40px;
    min-width: 100%;
}

/* BOOK CARD */

.book-card {
    background-color: var(--card-color);
    box-shadow: var(--box-shadow);
    border-radius: 15px;
    padding: 30px 40px;
    min-width: 100%;
    min-height: 100%;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    gap: 20px;


    /* PAPER FOLD */
  position: relative;
  
}

/* folding */
.read::before {
    content:"";
    position: absolute;
    top: 0px;
    right: 0px;
    border-style: solid;
    border-bottom-left-radius: 8px;
    border-width: 0 40px 40px 0;
    border-color: #dfd9d1 var(--content-color);
}

.book-card p {
    flex-basis: 0px;
    flex-grow: 1;
    min-width: 100%;
    letter-spacing: .2rem;
}

.book-title {
    font-weight: 700;
    font-size: 3rem;
    line-height: 2.8rem;
    font-family: 'Bilbo Swash Caps', cursive;
    color: var(--title-color);
}

.book-author, .book-pages {
    font-size: 1.2rem;
    line-height: 2rem;
    font-weight: 700;
    font-family: 'Kalam', cursive; 
}

.button-group {
    display: flex;
    justify-content: center;
    gap: 30px;
}

.button-group i {
    font-size: 1.5rem;
    background-color: var(--content-color);
    color: var(--button-color);
    width: 50px;
    height: 50px;
    padding: 20px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.button-group i:hover {
    cursor: pointer;
}

/* Modal */
.modal-container {
    opacity: 0;
    position: fixed;
    left: 0;
    top: 0;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: rgba(0, 0, 0, 0.3);
    width: 100vw;
    height: 100vh;
    transition: .4s;
    -webkit-transition: .4s;
    -moz-transition: .4s;
    -ms-transition: .4s;
    -o-transition: .4s;
    z-index: 0;
    pointer-events: none;
}

/* for the modal to be visible */
.active {
    opacity: 1;
    z-index: 2;
    pointer-events: all;
}

.add-book-form {
    display: flex;
    flex-direction: column;
    padding: 20px 30px;
    gap: 20px;
    background-color: var(--card-color);
    min-width: 400px;
    min-height: 40vh;
    text-align: center;
    position: absolute;
    left: 50%;
    top: 20%;
    transform: translate(-50%);
    -webkit-transform: translate(-50%);
    -moz-transform: translate(-50%);
    -ms-transform: translate(-50%);
    -o-transform: translate(-50%);
    border-radius: 10px;
    box-shadow: var(--box-shadow);
    user-select: none;
    z-index: 0;
}

.add-book-form h1 {
    color: var(--title-color);
}

input[type=text], input[type="number"] {
    height: 3.5vh;
    font-size: 1.2rem;
    padding: 20px;
    border-radius: 8px;
    border: 2px solid var(--header-color);
}

/* Toggle Button */
.toggle-button {
    display: flex;
    align-items: center;
    justify-content: space-around;
}

.label {
    font-size: 1.3rem;
    font-weight: 550;
    color: var(--title-color);
}

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
     transition: .4s;
}

input:checked   .slider {
    background-color: var(--button-color);
}

input:focus   .slider {
    box-shadow: 0 0 1px var(--button-color);
}

input:checked   .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
}

.slider {
    border-radius: 34px;
}

.slider:before {
    border-radius: 50%;
}

.button {
    padding: 10px;
    background-color: var(--button-color);
    border: none;
    border-radius: 8px;
    font-size: 1.5rem;
    color: var(--card-color);
    font-weight: 520;
    cursor: pointer;
}

.button:hover {
    background-color: #866749;
}

.modal-close-btn {
    position: absolute;
    font-size: 2.3rem;
    right: 10px;
    top: 2px;
    opacity: 0.2;
    cursor: pointer;
}

.modal-close-btn:hover {
    opacity: 1;
}

@media only screen and (max-width: 600px) {

    .container {
        display: flex;
        flex-direction: column;
        padding: 20px;
    }

    .add-book-btn {
        border: none;
        font-size: 2rem;
        border-radius: 50%;
        padding: 0 10px;
    }

    .book-grid {
        display: flex;
        flex-direction: column;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Library</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Bilbo Swash Caps&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Kalam:wght@300&family=Roboto:wght@100&display=swap" rel="stylesheet">
    <script src="https://kit.fontawesome.com/70237b74b7.js" crossorigin="anonymous"></script>

</head>
<body>
    <header >
        <div >
            <div >
                <span >
                    auto_stories
                </span>
                <h1 >Library</h1>
            </div>
            <button > </button>
        </div>
    </header>
    <main >
        <div >
            <div >
                <p >Don Quixote</p>
                <p >by Miguel de Cervantes</p>
                <p >992 pages</p>
                <div >
                    <i id="sample"  title="have read"></i>
                    <i  title="edit"></i>
                    <i  title="remove"></i>
                </div>
            </div>
        </div>
    </main>

    <!--Modal-->
    <div >
        <form  method="post">
            <span >&times;</span>
            <h1>Add New Book</h1>
            <input type="text" id="title" placeholder="Title" required>
            <input type="text" id="author" placeholder="Author" required>
            <input type="number" id="pages" placeholder="No. of Pages" required>

            <!-- Toggle Button-->
            <div >
                <p >Have you read this book?</p>
                <label >
                    <input type="checkbox" id="status">
                    <span ></span>
                </label>
            </div>

            <button  type="submit">Submit</button>
        </form>
  </div>
  </body>

For more context, I am actually doing an assignment project from The Odin Project and one of the objectives is to...

  1. Write a function that loops through the array and displays each book on the page.

CodePudding user response:

Change

//function that loops through the array and displays each book on the page
function addBookToLibrary() {
   for (let i = 0; i < myLibrary.length; i  ) {
      displayBook(myLibrary[i]);
   }
}

To

displayBook(myLibrary[myLibrary.length - 1]);

CodePudding user response:

  1. Each time you call addBookToLibrary, you add the books in the bookslibrary array to the dom . So it iterates over the previously added elements

  2. You just need to create a dom creation element when submitting the form same as :

//DOM Elements
const modal = document.querySelector('.modal-container');
const openModal = document.querySelector('.add-book-btn');
const closeModal = document.querySelector('.modal-close-btn');
const form = document.querySelector('.add-book-form');
const bookGrid = document.querySelector('.book-grid');
//open the add new book form
openModal.addEventListener('click', () => {
  modal.classList.add('active');
})
//close the form
closeModal.addEventListener('click', () => {
  modal.classList.remove('active');
})

//store book object in a simple array 
let myLibrary = [];

// object constructor
function Book(title, author, pages, status) {
  this.title = title;
  this.author = author;
  this.pages = pages;
  this.status = status;
}

//function that can take user’s input and store the new book objects into an array. 
function takeBookInfo() {
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    let book = new Book(title.value, author.value, pages.value, status.value);
    //store the new object into an array.
    myLibrary.push(book);
    console.log(myLibrary);
    console.log(book);
    //hide modal as soon as the form is submitted
    modal.classList.remove('active');
    //reset form as soon as the form is submitted
    form.reset();
    //loop through existing and new Book object in the array
    displayBook(book);

  })
}
takeBookInfo();

//function that loops through the array and displays each book on the page
for (let i = 0; i < myLibrary.length; i  ) {
  displayBook(myLibrary[i]);
}

//displays each book on the page
function displayBook(book) {
  const bookCard = document.createElement('div');
  bookCard.className = 'book-card';

  const bookTitle = document.createElement('p');
  bookTitle.className = 'book-title';
  bookTitle.textContent = book.title;
  bookCard.appendChild(bookTitle);

  const bookAuthor = document.createElement('p');
  bookAuthor.textContent = `by ${book.author}`;
  bookAuthor.className = 'book-author';
  bookCard.appendChild(bookAuthor);
  const bookPages = document.createElement('p');
  bookPages.className = 'book-pages';
  bookPages.textContent = `${book.pages} pages`;
  bookCard.appendChild(bookPages);

  bookGrid.appendChild(bookCard);
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Arial, Helvetica, sans-serif;
}

:root {
  --header-color: #49361c;
  --content-color: #eeeadf;
  --box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .2), 0 2px 3px 0 rgba(0, 0, 0, .2);
  --card-color: #fffbf7;
  --title-color: #362813;
  --button-color: #a58b63;
}


/* Header */

.header {
  min-height: 15vh;
  min-width: 100vw;
  box-shadow: var(--box-shadow);
  position: relative;
  z-index: 1;
}

.container {
  display: flex;
  background-color: var(--header-color);
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
}

.logo {
  min-height: 15vh;
  display: flex;
  align-items: center;
  gap: 25px;
  color: var(--content-color);
  text-shadow: 2px 2px 10px#362813;
}

.logo span {
  font-size: 6.5rem;
}

.title {
  font-family: 'Bilbo Swash Caps', cursive;
  font-size: 4rem;
  letter-spacing: 1.2rem;
}

.add-book-btn {
  border: none;
  font-size: 3rem;
  border-radius: 50%;
  padding: 0 10px;
}

.add-book-btn:hover {
  cursor: pointer;
  background-color: #e0dede;
}


/* Main Content */

.main-container {
  min-height: 100vh;
  min-width: 100vw;
  background-color: var(--content-color);
  padding: 40px;
  z-index: 1;
}

.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(20vw, 1fr));
  gap: 40px;
  min-width: 100%;
}


/* BOOK CARD */

.book-card {
  background-color: var(--card-color);
  box-shadow: var(--box-shadow);
  border-radius: 15px;
  padding: 30px 40px;
  min-width: 100%;
  min-height: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-items: center;
  gap: 20px;
  /* PAPER FOLD */
  position: relative;
}


/* folding */

.read::before {
  content: "";
  position: absolute;
  top: 0px;
  right: 0px;
  border-style: solid;
  border-bottom-left-radius: 8px;
  border-width: 0 40px 40px 0;
  border-color: #dfd9d1 var(--content-color);
}

.book-card p {
  flex-basis: 0px;
  flex-grow: 1;
  min-width: 100%;
  letter-spacing: .2rem;
}

.book-title {
  font-weight: 700;
  font-size: 3rem;
  line-height: 2.8rem;
  font-family: 'Bilbo Swash Caps', cursive;
  color: var(--title-color);
}

.book-author,
.book-pages {
  font-size: 1.2rem;
  line-height: 2rem;
  font-weight: 700;
  font-family: 'Kalam', cursive;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.button-group i {
  font-size: 1.5rem;
  background-color: var(--content-color);
  color: var(--button-color);
  width: 50px;
  height: 50px;
  padding: 20px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-group i:hover {
  cursor: pointer;
}


/* Modal */

.modal-container {
  opacity: 0;
  position: fixed;
  left: 0;
  top: 0;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: rgba(0, 0, 0, 0.3);
  width: 100vw;
  height: 100vh;
  transition: .4s;
  -webkit-transition: .4s;
  -moz-transition: .4s;
  -ms-transition: .4s;
  -o-transition: .4s;
  z-index: 0;
  pointer-events: none;
}


/* for the modal to be visible */

.active {
  opacity: 1;
  z-index: 2;
  pointer-events: all;
}

.add-book-form {
  display: flex;
  flex-direction: column;
  padding: 20px 30px;
  gap: 20px;
  background-color: var(--card-color);
  min-width: 400px;
  min-height: 40vh;
  text-align: center;
  position: absolute;
  left: 50%;
  top: 20%;
  transform: translate(-50%);
  -webkit-transform: translate(-50%);
  -moz-transform: translate(-50%);
  -ms-transform: translate(-50%);
  -o-transform: translate(-50%);
  border-radius: 10px;
  box-shadow: var(--box-shadow);
  user-select: none;
  z-index: 0;
}

.add-book-form h1 {
  color: var(--title-color);
}

input[type=text],
input[type="number"] {
  height: 3.5vh;
  font-size: 1.2rem;
  padding: 20px;
  border-radius: 8px;
  border: 2px solid var(--header-color);
}


/* Toggle Button */

.toggle-button {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.label {
  font-size: 1.3rem;
  font-weight: 550;
  color: var(--title-color);
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked .slider {
  background-color: var(--button-color);
}

input:focus .slider {
  box-shadow: 0 0 1px var(--button-color);
}

input:checked .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider {
  border-radius: 34px;
}

.slider:before {
  border-radius: 50%;
}

.button {
  padding: 10px;
  background-color: var(--button-color);
  border: none;
  border-radius: 8px;
  font-size: 1.5rem;
  color: var(--card-color);
  font-weight: 520;
  cursor: pointer;
}

.button:hover {
  background-color: #866749;
}

.modal-close-btn {
  position: absolute;
  font-size: 2.3rem;
  right: 10px;
  top: 2px;
  opacity: 0.2;
  cursor: pointer;
}

.modal-close-btn:hover {
  opacity: 1;
}

@media only screen and (max-width: 600px) {
  .container {
    display: flex;
    flex-direction: column;
    padding: 20px;
  }
  .add-book-btn {
    border: none;
    font-size: 2rem;
    border-radius: 50%;
    padding: 0 10px;
  }
  .book-grid {
    display: flex;
    flex-direction: column;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Library</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Bilbo Swash Caps&display=swap" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Kalam:wght@300&family=Roboto:wght@100&display=swap" rel="stylesheet">
  <script src="https://kit.fontawesome.com/70237b74b7.js" crossorigin="anonymous"></script>

</head>

<body>
  <header >
    <div >
      <div >
        <span >
                    auto_stories
                </span>
        <h1 >Library</h1>
      </div>
      <button > </button>
    </div>
  </header>
  <main >
    <div >
      <div >
        <p >Don Quixote</p>
        <p >by Miguel de Cervantes</p>
        <p >992 pages</p>
        <div >
          <i id="sample"  title="have read"></i>
          <i  title="edit"></i>
          <i  title="remove"></i>
        </div>
      </div>
    </div>
  </main>

  <!--Modal-->
  <div >
    <form  method="post">
      <span >&times;</span>
      <h1>Add New Book</h1>
      <input type="text" id="title" placeholder="Title" required>
      <input type="text" id="author" placeholder="Author" required>
      <input type="number" id="pages" placeholder="No. of Pages" required>

      <!-- Toggle Button-->
      <div >
        <p >Have you read this book?</p>
        <label >
                    <input type="checkbox" id="status">
                    <span ></span>
                </label>
      </div>

      <button  type="submit">Submit</button>
    </form>
  </div>
</body>

  • Related