Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap. Remember alert close action

I've tried to remember the close action in Twitter's Bootstrap alerts following this post (Using Bootstrap, have alert box remember close action)

I want users can not see the alert once they have closed it and the page reloads again.

I know that i must to store the status into a cookie, so I used the JQuery function suggested in the above example, but is not working. What am I doing wrong?

Fiddle -> http://jsfiddle.net/kFy5y/

Thanks in advance!!

jQuery(function( $ ){

    // Check if alert has been closed
    if( $.cookie('alert-box') === 'closed' ){

        $('.alert').hide();

    }

     // Grab your button (based on your posted html)
    $('.close').click(function( e ){

        // Do not perform default action when button is clicked
        e.preventDefault();

        /* If you just want the cookie for a session don't provide an expires
         Set the path as root, so the cookie will be valid across the whole site */
        $.cookie('alert-box', 'closed', { path: '/' });

    });

});

Alert

<div class="alert alert-info fade in">            
            <button type="button" class="close" data-dismiss="alert">×</button>
            <strong> ALERT BODY</strong>
</div>
like image 816
ɐsɹǝʌ ǝɔıʌ Avatar asked Apr 02 '13 09:04

ɐsɹǝʌ ǝɔıʌ


2 Answers

You are using $.cookie('alert-box') which is not a standard jQuery function but a method implemented in a library like jquery-cookie.

So you need to add this library or a similar one to be able to save cookies using jQuery.

like image 135
RRikesh Avatar answered Nov 15 '22 05:11

RRikesh


Here is an general solution that works on every page for every alert with an ID.

//////////////////////////////////
    //remember close BS alert

    function showUnDismissedAlerts(){
        //if there is no localStorage, just show all alerts and return
        if (!localStorage.getItem(`dismissedAlerts_${document.title}`)) {
            $('.alert').show()
            return;
        }
        //get dismissed alert ID's
        let dismissedAlerts = JSON.parse(localStorage.getItem(`dismissedAlerts_${document.title}`))
        //look for each alert if it was dismissed
        $('.alert').map((index, el) => {
            //get the alert ID
            let alertId = $(el).attr('id')
            //if there is no ID, return (next alert)
            if (!alertId) return;
            //assuming the alert isn' dismissed
            let dismissed = false
            for (let i = 0; i < dismissedAlerts.length; i++) {
                //if the alert is present, it was dismissed, therefore set dismissed to true and exit for
                if (alertId == dismissedAlerts[i]) {
                    dismissed = true
                    break;
                }
            }
            //if alert isn't dismissed, show it
            if (!dismissed) $(el).show()
        })
    }

    //fires if there are alerts on page
    if ($('.alert').length > 0) {
        $('.alert').on('click', '.close', function (e) {
            e.preventDefault()
            //get alert element
            let parent = $(this).parent()
            //get alert ID
            let id = $(parent).attr('id')
            //return if no ID is defined
            if (!id) return;
            //get all dismissed alerts, based om localStorage. The document title is in key to prevent long data arrays
            if (!localStorage.getItem(`dismissedAlerts_${document.title}`)) {
                //if storage doesn't exists, add it with the dismissed alert ID
                localStorage.setItem(`dismissedAlerts_${document.title}`, JSON.stringify([id]))
            } else {
                //localStorage exists, so get it and parse it to an array
                let alerts = JSON.parse(localStorage.getItem(`dismissedAlerts_${document.title}`))
                //assuming the alert isn't already dismissed
                let alreadyDismissed = false
                //loop trough dismissed alerts and find out if there is a double
                alerts.map(alertId => {
                    //if id is already there, return
                    if (alertId == id) {
                        alreadyDismissed = true
                        return;
                    }
                })
                //if id alert ID isn't added, so add it an store the new dismissed alerts array
                if (!alreadyDismissed) {
                    alerts.push(id)
                    localStorage.setItem(`dismissedAlerts_${document.title}`, JSON.stringify(alerts))
                }
            }
        })

        //show all the undismissed alerts
        showUnDismissedAlerts()
    }
.none{
  display: none;
}
<!-- css -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="alert alert-info alert-dismissible none" role="alert" id="my_alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">×</span>
  </button>
  <strong>I'm a alert</strong>
</div>

<!-- script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
like image 38
Roy Zon Avatar answered Nov 15 '22 04:11

Roy Zon