user991830 user991830 - 5 months ago 170
Javascript Question

jQuery to remove div & set cookie to never show again

I am using the following html / jQuery to remove a div after clicking a link.

When clicking the link, I also need to set a cookie that keeps the div as 'removed' when the same visitor comes back to the site.

HTML

<div id="close-me">
bye bye - being removed on click of close link
</div>

<p>
<a href="#" class="close-div">Close</a>
</p>


jQuery

jQuery(document).ready(function( $ ) {
jQuery(".close-div").click(function(){
jQuery("#close-me").remove();
});
});


I would assume jquery.cookie.js is the best solution.

How would I do this?

JSfiddle here

Answer

jQuery Cookie is no longer maintened, so I would not go for it. Instead, you can use js-cookie which is recommended as replacement by the dev team of jQuery Cookie.

Once loaded, it will be :

jQuery(document).ready(function($) {
    if (typeof Cookies.get('hide-div') !== 'undefinied') {
        $("#close-me").remove();
    }

    $(".close-button").click(function() {
        $("#close-me").remove();
        Cookies.set('hide-div', true);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.2/js.cookie.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="close-me">
  <i class="close-button">&times;</i>
  Your content here
</div>