Book list in Javascript

Today i will show you how to create a book list with pure JavaScript with modular approach.

 
html of application

Demo

 
<body>
	 <div class="container">
        <div id="form-block">
      <h1>Add Book</h1>

  <div class="form-group">
    <label>Title</label>
     <input type="text" id="title" class="form-control">
   
  </div>
<div class="form-group">
    <label>Author</label>
     <input type="text" id="author" class="form-control">
   
  </div>
  <div class="form-group">
    <label>Isbn</label>
     <input type="text" id="isbn" class="form-control">
   
  </div>
       <button type="submit" id="submitButton" class="btn btn-primary mb-2">Submit</button>
  
 <table class="table"  id="book-list">
  <thead>
    <tr>
      <th>Title</th>
      <th>Author</th>
      <th>ISBN</th>
      <th>Delete Item</th>
    </tr>
  </thead>
  <tbody>
    
   
  </tbody>
</table>

    </div> 
    
    </div>
  </body>
	<script src="app.js">
	</script>
app.js 
 
//  BOOK CONTOLLER MODULE
var BOOKController = (function() {
    var Books = function(id, title, author, isbn) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    };

    var data = {
        books: []
    };
    return {
        addBooks: function(titleData, authorData, isbnData) {
            var newBook, ID;
            //[12,24,51,62,75,88,98]
            console.log(data.books)
            if (data.books.length > 0) {
                ID = data.books[data.books.length - 1].id + 1;
            } else {
                ID = 0;
            }
            //console.log(ID)
            newBook = new Books(ID, titleData, authorData, isbnData);

            data.books.push(newBook);
            return newBook;
        },
        deleteBook: function(id) {
            //alert(typeof id)
            var ids, index;
            ids = data.books.map(function(current) {

                return current.id;
            });
            index = ids.indexOf(id);

            if (index !== -1) {
                data.books.splice(index, 1)
            }
        },
        testing: function() {
            console.log(data);
        }
    };
})();
var Books = function(title, author, isbn) {
    title = this.title;
    author = this.author;
    isbn = this.isbn;
}

//UI CONTOLLER MODULE
var UIController = (function() {
    var DOMStrings = {
        inputTitle: '#title',
        inputAuthor: '#author',
        inputIsbn: '#isbn',
        submitBtn: '#submitButton',
        booklist: '#book-list'
    };
    return {
        getInputs: function() {
            return {
                title: document.querySelector(DOMStrings.inputTitle).value,
                author: document.querySelector(DOMStrings.inputAuthor).value,
                isbn: document.querySelector(DOMStrings.inputIsbn).value
            };

        },
        addBookslist: function(obj) {
            var html
            //create html with placeholder
            html = '<tr id=' + obj.id + '><td>' + obj.title + '</td><td>' + obj.author + '</td><td>' + obj.isbn + '</td><td>X</td></tr>';
            //insert in DOM
            document.querySelector(DOMStrings.booklist).insertAdjacentHTML('beforeend', html);

        },
        clearFields: function() {
            var fields, fieldsArray;
            fields = document.querySelectorAll(DOMStrings.inputTitle + ',' + DOMStrings.inputAuthor + ',' + DOMStrings.inputIsbn);
            fieldsArray = Array.prototype.slice.call(fields);
            //console.log(fieldsArray)

            fieldsArray.forEach(function(current) {
                current.value = "";
            });
            fieldsArray[0].focus();
        },
        showAlert: function(message, customClass) {
            //Create div
            var newDiv, newContent, currentDiv;
            newDiv = document.createElement('div');
            newDiv.className = "alert" + ' ' + customClass;
            newContent = document.createTextNode(message);
            newDiv.appendChild(newContent);
            currentDiv = document.querySelector(".container");
            document.body.insertBefore(newDiv, currentDiv);
            setTimeout(function() {
                document.querySelector('.alert').remove();
            }, 3000)
        },
        deleteBookList: function(deleteId) {
            document.getElementById(deleteId).remove();
        },
        getDOMStrings: function() {
            return DOMStrings;
        }
    };
})();

//APP CONTOLLER MODULE
//Connecting UI and BOOK MODULE WITH APP CONTOLLER(GLOBAL)
var APPController = (function(BOOKCtrl, UICtrl) {
    var setupEventListners = function() {
        var DOM = UICtrl.getDOMStrings();
        document.querySelector(DOM.submitBtn).addEventListener('click', ctrAddItem)
        document.addEventListener('keypress', function(event) {
            if (event.keyCode === 13 || event.which === 13) {
                ctrAddItem();

            }
        });
        document.querySelector(DOM.booklist).addEventListener('click', ctrDeleteItem);
    };

    var ctrAddItem = function() {
        var inputs, newItem;
        //get input data
        inputs = UICtrl.getInputs();
        //console.log(inputs)
        if (inputs.title !== "" && inputs.author !== "" && inputs.isbn !== "") {
            var newItem = BOOKCtrl.addBooks(inputs.title, inputs.author, inputs.isbn);
            //add the new item in UIController
            UICtrl.addBookslist(newItem);
            UICtrl.showAlert('Added Succssfully.', 'alert-success');
            //Clear fields
            UICtrl.clearFields();
            //console.log(inputs)
        } else {
            UICtrl.showAlert('Please fill all fields', 'alert-danger')
        }

    };
    var ctrDeleteItem = function(event) {
        var bookId;
        bookId = event.target.parentNode.parentNode.id;
        if (bookId) {
            BOOKCtrl.deleteBook(parseInt(bookId));
            UICtrl.deleteBookList(bookId);
            UICtrl.showAlert('Deleted Succssfully.', 'alert-danger');
        }
    };
    return {
        init: function() {
            console.log('App started');
            setupEventListners();
        }
    };
})(BOOKController, UIController);

APPController.init();

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *