Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal and cookie

I have created a bootstrap modal popup and it appears and disappears perfectly. What I need to do is check to see if there is a cookie stored and only have the popup appear once while the user is on the site. I have a close button on it too. At the moment it appears every time I refresh the page and I'm not sure how to get it to work. I have seen a couple of examples by googling but nothing works for me. Can anyone help? Thanks

Here is my Javascript:

$(document).ready(function () {
    if (document.cookie != "") {
        $("#myModal").modal("show");
        $("#myModalClose").click(function () {
          $("#myModal").modal("hide");
        });
    }
});

Here is my HTML:

<div id="myModal" class="modal fade in">
    <div class="inner-modal">
        <div class="modal-container">
            <p>some text</p>
            <button class="close" data-dismiss="modal" data-target="#myModal">Hide this message</button>
        </div>
    </div>  
</div>
like image 366
fnk Avatar asked Oct 29 '14 12:10

fnk


People also ask

What is a modal in bootstrap?

Modals are built with HTML, CSS, and JavaScript. They're positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead. Clicking on the modal “backdrop” will automatically close the modal. Bootstrap only supports one modal window at a time.

Is bootstrap modal responsive?

Bootstrap modals are supposed to be responsive by default. Something to look out for is if you have a width set on your Modal. For example I had a form body container inside of my modal with a height of 40rem.


1 Answers

Your logic is a bit back to front. You need to check if no cookie has yet been set then show the modal. Also you need to set the cookie afterwards so it doesn't happen again.

$(document).ready(function () {
    //if cookie hasn't been set...
    if (document.cookie.indexOf("ModalShown=true")<0) {
        $("#myModal").modal("show");
        //Modal has been shown, now set a cookie so it never comes back
        $("#myModalClose").click(function () {
            $("#myModal").modal("hide");
        });
        document.cookie = "ModalShown=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<div id="myModal" class="modal fade in">
    <div class="inner-modal">
        <div class="modal-container">
            <p>some text</p>
            <button id="myModalClose" class="close" data-dismiss="modal" data-target="#myModal">Hide this message</button>
        </div>
    </div>  
</div>
like image 158
DavidG Avatar answered Oct 28 '22 18:10

DavidG