How to: create an alert popup with jQuery

Alert popups are a great way to notify your visitors. Since I recently had to implement an alert popup with jQuery on an older site, I thought it could be interesting to share its code.

A blue and purple illustration of a lo-fi popup illustration.

I wanted my alert popup to achieve a couple of things:

  • It should be highly reusable
  • If dismissed by a user it should stay dismissed
  • It should be easy to implement and expand

The following example is made to work with jQuery - but it's not dependent on it. The same result could be easily achieved with Javascript.

Check out the source code to our alert popup on this Codesandbox:

The most interesting part of this code is how we use Cookies to save the information that the user has dismissed the notification.

var currentPopupHash = "1234921347219834";

The above is our hash. This can be any kind of unique string. You can use numbers or text - but remember, it has to be unique. This identifies the current version of our alert.

document.cookie = "popup=" + currentPopupHash;

When we dismiss the popup, we run the above code. This saves a cookie with our hash. This means that as our window is loading we can check if the current popup has been dismissed by our user.

if (
  document.cookie.replace(
    /(?:(?:^|.*;\s*)popup\s*\=\s*([^;]*).*$)|^.*$/,
    "$1"
  ) === currentPopupHash
) {
  console.log("hide notification");
  $("#notification-popup").hide();
}

document.cookie.replace will extract our popup cookie from our user's browser and compare it with our currentPopupHash. If that cookie exists and is the same as currentPopupHash, then we hide our notification.

What makes this code so useful is that by just changing currentPopupHash, we can make sure that the notification will again be shown to the user. So if you need to inform your visitors about something new, you can just modify currentPopupHash and the message and the notification will start to pop-up again.

And there you have it! Those are the basics you should need to create your first pop up. However, if I've missed something or you have any questions, feel free to comment and let me know!