Magento2 | PWA | GraphQL

Magento2 Display/Hide content based on Magento Cookies With jquery


With the use of Magento2 Cookies we are able to show/hide content if cookies is set or not. These words sounds like a simple and easy task in simple PHP application. But when you are working with Magento2 then you should be aware about how to use magento cookies in jquery. I will show you how to do this basic stuff.

Suppose in footer i have to show some HTML like popup or any image with close button on it. when user click on close button after that HTML should never display. Again in fresh browser it should display again. hope you understand and face similar kind of situation in many of your projects.

first i am writing a simple HTML div tag.

Now after that you have to write Jquery and use Magento2 Cookies functionality to check cookie is set or not then do your logic/code accordingly.
<script type="text/javascript">
      require([ 'jquery','mage/cookies'], function ($) {
        var lowestprice = "promotional-sale-banner";
        if (!$.mage.cookies.get(lowestprice)) {
        var lowesthtml = '';// set your HTML with close btn class/id
        }
        $(".promotional-sale-banner").append(lowesthtml);
        //var lowestprice = "";
        $(".close-btn").click(function () {
            $.mage.cookies.set(lowestprice, "shown");
        });
    }); 
</script>
0 Comments On "Magento2 Display/Hide content based on Magento Cookies With jquery"

Back To Top