Skip to main content

How to use and purpose of localstorage in javascript

The localStorage properties allow saving key/value pairs in a web browser. You can access it from one page to another page like a session. But it is stored in the browser. You can set and get the value, and also remove the item from localStorage.

  • Show modal using localStorage in javascript

    set localStorage item with key openModal and value #addEventModal


    <a id="addEventBtn" href="main.html"> Add Event </a>
    <script src="" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
            $('#addEventBtn').on('click', function(e){
                localStorage.setItem('openModal', '#addEventModal');
                let href =;

    Get the localStorage with getItem method and show modal if it is not null and after that remove item from storage


    <div class="modal" id="addEventModal">
       <div class="modal-dialog ">
           <div class="modal-content">
               <div class="modal-header">
                  <h4 class="modal-title">Modal title</h4>
                   <button type="button" class="close" data-dismiss="modal">&times;</button>
              <div class="modal-body">
            <p>Modal body text goes here.</p>
               <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                   <button type="button" class="btn btn-primary">Save changes</button>
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
    var modalId = localStorage.getItem('openModal');
    if(modalId != null){
        $(modalId).modal("show"); //use modal with id addEventModal

    It will help you to set the localStorage with modal id in one page using javascript and will show modal to another page after the redirection and remove the item after showing the modal so that on next visit modal did not show. 

    setItem in one page and show modal, remove localStorage item using removeItem after showing the modal

  • Back to code snippet queries related jquery