Search

Displaying popups in WordPress with Javascript Cookies

In this guide, we will see a way to display a popup on WordPress sites. We’ll present the same popping message to your visitors without using a plugin and will help with Cookies. In this case, we will use the Javascript Cookie library to prevent the same popup from jumping again once the visitor has clicked on a specific button.

Since we are not using a plugin, we can of course design the message and determine its behavior exactly as we want. So if you are promoting a specific product in WooCommerce stores, or if there is some new functionality or new article that you want to promote in your blog, this is a great option to inform your visitors without annoying them too much.

Let’s briefly say for those who don’t know, that Cookies are actually small files saved on your computer by the browser and contain your personal settings for certain websites. For example, if you added products to the shopping cart in some digital store, it’s likely that if you exit and return to the store – the products in the cart will still be saved and this is done using Cookies.

For more information on cookies, take a look at the post What are cookies (Cookies) and how to work with them in JavaScript.

What Does This Guide Have to Do with GDPR Regulations?

If you’re not familiar, there’s a law called the Cookies Law that comes as part of the GDPR regulations that recently came into effect. If even a small percentage of the audience on your site comes from the European Union (EU), you certainly need to consider this law, and ignorance of the law does not exempt.

That’s why recently you’re probably encountering messages about the use of Cookies on many websites, these exist to inform your audience that your site uses Cookies. Such messages can feel superfluous due to the high frequency of the use of Cookies on sites, but there are less web-savvy users who aren’t aware at all that their behavior is being tracked.

Therefore, beyond the GDPR regulations, the implementation of these messages shows transparency to your visitors and is likely to be appreciated. The way we will describe in this guide is a great way to implement these messages on your site and cover (partially) yourself in this regard.

But we are not here to talk beyond that about the Cookies Law and GDPR regulations, it is not the purpose of the post. Let’s get straight to the task and see how to add a popup to the visitor as long as he has not clicked on a button we will define, and we will do that (ironically) using Cookies. Let’s start, these are the steps for displaying a popup on WordPress sites using Javascript Cookie.

Loading the Javascript Cookie Library in WordPress

Download the library from the following link (the link contains the relevant file only) and copy it to the folder in your child theme. In our case, we’ll copy it to a folder named js in the child theme that you can create if it doesn’t exist.

The Javascript Cookie library by the way supports all browsers and has no dependency on any other library.

Now, as we’ve seen in many articles on this blog – the correct way to add assets (Javascript and CSS files) in WordPress is done as follows using the function wp_enqueue_scripts:

<?php
/***** BEGIN HERE *****/
function add_scripts_to_wordpress() {
	wp_register_script( 'js_cookie', get_template_directory_uri() . '/js/js.cookie.min.js', '1.0.0', true );
	wp_enqueue_script( 'js_cookie' );
}
add_action( 'wp_enqueue_scripts', 'add_scripts_to_wordpress' );

Ensure that the file is properly loaded and if it is not loaded check again if the path to the file is properly defined. Also, note that you are omitting the opening PHP tag.

Creating the Markup for the Popup

We will add the Markup, that is, the necessary HTML that displays the message in the footer of our WordPress site as follows:

<?php
/***** BEGIN HERE *****/
function cookie_notice_popup() { ?>
    <div class="cookie-notice">
    <div class="cookie-notice-inner">
        <div class="content-cookie">Hey! We use Cookies to ensure that your browsing experience will be optimal. Continuing to browse the site means that you accept the use of Cookies. Read more <a href="<?php echo get_page_link('xxx'); ?>">in the privacy policy.</a></div>
            <button class="button-cookie">Okay!</button>
        </div>
    </div>
    <?php
}
add_action('wp_footer','cookie_notice_popup');

It should be noted that in addition to the confirmation button, we also display a link to your site’s privacy policy page using the function get_page_link. You are welcome to remove this link, but if you choose to use it be aware that you change xxx to the identifier (ID) of your privacy policy page or any page you choose in line number 6.

If you don’t know how to find that identifier, take a look at the first part of the post Displaying ID of Pages and Posts.

Designing the Popup Using CSS

You can of course design the message as you wish, but we will present one option for displaying the message at the bottom of your site. Of course, we will use CSS to do this. Add the following code to the CSS file in your child theme:

.cookie-notice {
    position: fixed;
    bottom: 0;
    background: rgba(24, 24, 24, 0.9);
    width: 100%;
    z-index: 9999;
    padding: 20px 10px;
    display: none;
    text-align: right;
    color: #fefefe;
    font-size: 14px;
}

.cookie-notice-inner {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

.content-cookie-inner > a {
    color: #fefefe !important;
}

button.button-cookie {
    background: none;
    border: 2px solid #fefefe;
    border-radius: 28px;
    color: white;
    font-size: 14px;
    padding: 5px 26px;
    margin-top: 14px;
}

@media (min-width: 768px) {

    button.button-cookie {
        margin-top: 0;
    }

    .cookie-notice-inner {
        flex-direction: row;
    }

}

We use Flexbox to simplify things. It should also be said that this is only an example, and you will probably need to play with the CSS to adapt it to your WordPress site and the desired design.

Keep in mind that the element we created is not displayed at this stage (display:none) – we will only display it in the next step using Javascript assuming the Cookie (which we will soon create) does not exist for the visitor.

We will display the popup after the site loads if the Cookie does not exist

Now the more interesting stage. We will cause the popup message we created to pop up after the site or page is loaded and we will ensure that by clicking on the button in the popup – a Cookie will be created for the user and it will close.

With that same Cookie, we will make sure that the next time the visitor comes to the site, or alternatively, on the next page the visitor reaches if they are still on the site – the popup will not appear again. Here is the code:

function cookieInit() {
    var ourCookie = Cookies.get('ourCookie');
    if (ourCookie) {
        return false;
    } else {
        openCookiePopup();
    }
}


function openCookiePopup() {
    setTimeout(function () {
        $('.cookie-notice').fadeIn(300);
    }, 4000);
}

cookieInit();

The first function in this code (cookieInit) checks if a Cookie named OurCookie exists for the visitor. If it exists, the function exits (returns false), and if it does not exist, it calls the function named openCookiePopup. This determines that after 4 seconds the popup element we created will be displayed.

Note that this code should only be loaded after the Javascript Cookie library has been loaded.

Adding the Part That Determines Clicking on the Confirmation Button Will Hide the Message and Create a Cookie

We will add a few more lines to the previous code that determine that clicking the button will hide the element and create a Cookie for the visitor, so that the next time the popup will not be displayed due to the condition in the first function:

$('.button-cookie').on('click', function () {
    $('.cookie-notice').fadeOut(300);
    Cookies.set('ourCookie', 'yes', { path: '/' });
});

In the code presented under this part of the article, we used two Javascript functions – one called Cookies.get and the other Cookies.set. As their names suggest, one reads a specific Cookie and the other creates a Cookie.

In our case, we did not define any expiration for the Cookie we created, so when the user closes the popup – they will not see it again ever (unless they manually delete the Cookie). We are basically done, you can check the result…

Maybe this is the place to mention that when you use and develop code related to Cookies, in many situations you will want to delete one Cookie or another for testing purposes. There’s an extension for Chrome that allows you to do this easily, and it’s called EditThisCookie, surely you’ll find it useful if you work with Cookies.

A Few More Words About the Javascript Cookie Library

The Javascript Cookie library is an excellent library that has undergone extensive tests, supports all browsers, and does not depend on any other library. It’s lightweight (~900 bytes gzipped!) and that’s an important matter for optimizing and speeding up your WordPress site. We’ll explain a bit about working with Cookies through it:

To create a Cookie for all pages on the site:

Cookies.set('name', 'value');

To create a Cookie valid for a week for all pages on the site:

Cookies.set('name', 'value', { expires: 7 });

To create a Cookie valid for a week and valid only for the current page:

Cookies.set('name', 'value', { expires: 7, path: '' });

To read a Cookie:

Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined

To read all the Cookies:

Cookies.get(); // => { name: 'value' }

To remove a Cookie:

Cookies.remove('name');

To remove a Cookie which is valid for the current page:

Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!

More information about the options of the Javascript Cookie library can be seen on the library’s GitHub page.

In Summary

In this guide, we saw how to display a popup on WordPress sites and used a Cookie to check whether any action was taken according to which it is determined whether to display the popup again or not. I believe you will find many situations in which you will want to use messages dependent on Cookies when you develop in WordPress, whether for yourselves or if you are providing services to other companies/sites.

If you have other ways to do this, or if there’s another library you use, feel free to tell. I hope this post is relevant for you, you are welcome to make claims and ask questions as always… 🙂

Roee Yossef
Roee Yossef

I develop websites & custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Quick Navigation

Up!
Blog