JS cookie (in a Rails app)
setTimeout function. But along with this task came some other considerations as well.
This modal happens to live in the layout file, and thus can be seen on any page in the entire application. It was being triggered by a button that also lives on every page. The client wanted the modal to be more prominent, which is why we needed it to pop up automatically after 15 seconds. However, it clearly shouldn’t pop up every time the user visits a new page, that would be the most annoying thing ever. So, how could I make the modal pop up the first time the user visits a page, but never again (or again after a specified amount of time)? Well, it’s cookie time!
I decided to set a cookie that would expire after one day, so that the user would only see the modal again after one day had passed.
Here’s how the cookie works:
- User visits the site
- After 15 seconds, the modal pops up
- Cookie is set on that modal
- On page reload, a JS function looks for the cookie. If the cookie is there, no modal. If cookie is not there, modal.
- After one day cookie expires. User visits the site again… modal!
Here’s how I did it (in a Rails app):
- Require the file in
//= require js.cookie
- Tip: Require it higher up. 3rd party includes should go higher in case they’re needed in other files (which will be lower).
A couple things are worth mentioning here:
- On line 5, where the cookie is set, the first parameter is the name of the modal, and the second is the value. That value can only be a string, not a boolean. It’s a little annoying, but it is what it is.
- Look up at line 2, where the function checks the value of the cookie. If the value were a boolean, it could be written more clearly (false), but it’s a string and we have to live with that. So if the value is anything but the string ‘true’, the modal shows.
- On line 5 again, you can set the number of days after which the cookie expires. In this case, it’s one day.
As explained above, once the window loads, this JS function checks to see if the modal has a cookie. If there’s no cookie, the modal pops up after 15 seconds, then sets a cookie. This way, the modal will pop up only if it has not been shown before (e.g. only the first time visitor will see the modal).
So that’s how I used the cookie to show and not show the modal. Thanks for reading!