Saving Bootstrap Data - Modals, Tags and Notifications

Check out my code snippets on this example/demo page.

 

/* Messages Modal */
$(document).ready(function(){
    var informer = $("#messageInformer a");
    var refreshBadge = function(messageCount) {
        var badge = informer.find(".badge");
        
        if (messageCount > 0) {
            if (!badge.length) {
                informer.text("Messages ");
                informer.append("<span class=\"badge\">" + messageCount + "</span>");
            } 
            
            else {
                badge.text(messageCount);
            }
        } 
        
        else {
            // informer.text("No messages");
            informer.text("Messages ");
            informer.append("<span class=\"badge\">" + messageCount + "</span>");
        }
    };

    var buildMessage = function(message) {
        var htmlMessage = "<div class=\"alert fade in\">";
        
        htmlMessage += "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-lable=\"close\" data-id=\"" + message.id + "\">&times;</a>";
        htmlMessage += "<strong>" + message.title + "</strong>";
        htmlMessage += "<p>" + message.text + "</p>";
        
        return htmlMessage;
    }

    // Messages To Display
    var messages = [
        { 
        id: "1", 
        title: "Title 01:",
         text: "<ul> \
         <li>List Item</li> \
         <li>List Item</li> \
         </ul> \
         <br/> \
<p>Paragraph</p> \
<p>E-Mail: <a href=\"mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d7dfd3dbdef2d3d6d6c0d7c1c19cd1dddf">[email protected]</a>\"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27424a464e4b67349434542344542e40444a">[email protected]</a></a></p> \
        " 
        },
        { 
        id: "2", 
        title: "Title 02:", 
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam volutpat velit et vehicula vulputate." 
        },
        { 
        id: "3", 
        title: "Title 03:", 
        text: "Quisque viverra nisl ut arcu eleifend aliquam. Ut faucibus efficitur nibh, sit amet tincidunt est volutpat non." 
        }
    ];

    refreshBadge(messages.length);

    informer.on("click", function(e) {
        e.preventDefault();
        var modalBody = $(".modal-body");
        modalBody.empty();
        for (var i = 0; i < messages.length; i++) {
            modalBody.append(buildMessage(messages[i]));
        }
        
        if (messages.length == 0) {
            $('.modal-body').text('There are no more messages to display.');
        }
    });

    $("body").delegate(".alert .close", "click", function() {
        var messageId = $(this).data("id");
        // AJAX 
        messages = messages.filter(function(el) {
            return el.id != messageId;
        });
        
        if (messages.length == 0) {
            // $("#messagesModal").modal("hide");
            $('.modal-body').text('There are no more messages to display.');
        }
        
        refreshBadge(messages.length);
    });
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<p data-toggle="modal" data-target="#messagesModal" id="messageInformer"><a href="#">Messages <span class="badge"></span></a>
</p>

<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Messages</h4>
      </div>

      <div class="modal-body">
      </div>

      <div class="modal-footer">
        <div class="col-md-8 pull-left">
        </div>

        <div class="col-md-4">
          <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div> 

Is there a way I can ensure the data of the modal, badge, and alerts is preserved when the page is refreshed?

For instance, if one of the three messages is deleted and the page is refreshed, only two messages should remain available.

Answer №1

I will not be making any edits to my response because the previous answer was for a sample purpose, aimed at those looking to implement sessionStorage. Here, I will address your specific issue by providing additional code that should resolve your problem.

In this solution, we are utilizing the sessionStorage technique to manage previously removed elements within a single tab. For testing purposes, I have not included a fiddle link, so you will need to copy the provided code and run it in your local environment.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

</head>

<script>
 // JavaScript code here
</script>

    <!-- Body content goes here -->

</html>

Answer №2

If you want to store data for your webpage, you have the option of using either sessionStorage or localStorage.

localStorage is used for storing data without an expiration date.

sessionStorage is used for storing data that will be lost when the browser tab is closed, essentially lasting only for one session.

Instead of making changes to your code directly, I'm providing a sample code snippet below that can guide you on how to achieve your desired functionality:

All you need to do is understand the logic behind the code and implement it in your own script. Good luck!

<html>
<head>
<script src=" http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function(){

    var id = sessionStorage.getItem("id");
    if(id != null){
        var temp = id.split(',');   
        $.each(temp, function(index, value){
                        $('#'+value).hide();
        });
    }
});

function deleteItem(obj, object){

var id = sessionStorage.getItem("id");

if(id == null){
    sessionStorage.setItem("id", obj);
}else{
    var str = id.split(',').join();
    str = str + ','+ obj
    sessionStorage.setItem("id", str);
}
$(object).parent().hide();
}
</script>

</head>
<body>

<h2 id="1">Header 1 &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="deleteItem('1', this)">X</a></h2>
<h2 id="2">Header 2 &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="deleteItem('2', this)">X</a></h2>
<h2 id="3">Header 3 &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="deleteItem('3', this)">X</a></h2>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can Big Data flow on Mongo DB be effectively simulated?

My idea involves creating a server with routes and models to be hosted on Heroku for processing requests. I plan to make incremental requests to the server until they qualify as Big Data. I suspect there may be limitations on how many consecutive requests ...

Increase the count for each category with the help of JavaScript

Currently, I am working on an application using PHP and have 180 vendors registered in the database. Each vendor has a unique ID stored in the database. I need to create a system where every time a user clicks on the "view details" button for a specific ...

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

Can the parcel bundler dist folder be customized for decoration?

After compiling code with parcel using the command parcel src/index.html, all files are generated inside the dist folder. However, I am looking for a more organized way to manage these files once my website is complete. Ideally, I want separate folders suc ...

Testing Ajax code encounters error

Currently, I am running a code test with Jasmine and setting up a mock object for the ajax method. spyOn($,'ajax').and.callFake(function(e){ console.log("is hitting"); }) In order to test the code snippet below: $.ajax({ url: Ap ...

What is the best method for submitting a form individually using jQuery?

Below is a basic form submission code using jQuery: <script> $(document).ready(function(){ $("form#submit").submit(function() { var fname = $('#fname').attr('value'); var lname = $('#lname').at ...

Leveraging ruby/watir/page_object for testing a jQuery UI autocomplete feature (AJAX)

Currently, I am utilizing a combination of jRuby, watir-webdriver, and Page Object for conducting tests on a web application. Within the application, there exists a jquery autocomplete widget that yields responses from the backend database following an un ...

Could there be a coding issue stopping <div class="rating"> from aligning more centrally along the horizontal axis on the screen?

Just wondering, could there be something in my code that's preventing <div class="rating"> from moving closer to the center? And is there a way to make it move closer horizontally? (On a side note, CSS layout and positioning still puzz ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

Ways to display an image overlay on hover using sprite sheets

Is there a way to make a line appear, around 10px in size, when hovering over an image at the bottom of that image? I came across this effect on MTV's website within their "You would also like these" section below each post. They utilized css-backgro ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

Error: The `Field` component encountered a failed prop type validation due to an invalid prop `component` after upgrading to MUI version

Encountered an error when migrating to Material ui v4 Failed prop type: Invalid prop component supplied to Field. in Field (created by TextField) This error points to the redux form field component export const TextField = props => ( <Field ...

What is the best way to extract text/html that appears between two consecutive <input> tags?

Is there a straightforward method to extract the text or HTML content located between input tags, even though these tags do not require closing tags? For instance, in the example below, I am looking to retrieve <b>Bob and Tim</b><br>Tim & ...

The Protractor test scripts are running with lightning speed, outpacing the webpage loading time

Seeking guidance on automating an angular js website with login functionality. Need to click on the sign-in link and enter username and password, but facing issues with script execution speed being faster than page load. Here is my approach for handling th ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

Troubles with CSS Child Hover, Rotation, and Clipping in Pie Chart styling

The issue I am facing is with a 3-section pie chart where all sections look virtually identical. However, the :hover effect does not trigger on the first section, but it works on the other two. Each element has an equal number of overlapping parent divs, ...

Retrieve a specific HTML using the returned jQuery AJAX POST request

$('#form-register').change(function() { var i_username = $('input#input-username').val(); var i_password = $('input#input-password').val(); var i_company = $('input#input-company').val(); var i_phone ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

Simple way to automatically reload your script using an npm server

Testing out a sample javascript code snippet. Locating a script named simple.js in the demos directory. Executing the demo using the command yarn build-demos && http-server demos/ The script simple.js is compiled to simple_bundle.js and the serv ...