JavaScript
Article

Creating an Opt-in Monster Clone with jQuery

By David Turnbull

Without a doubt, the most effective way to build an email list is to create a modal that appears when a visitor stumbles across your website. This modal will then contain an opt-in form that they simply can’t ignore (usually with a compelling bribe to hand over their email, like a free download of some sort). This approach is not without its share of controversy, but:

  1. They remain incredibly effective.
  2. The complaints are from a vocal minority.

To create these modals, most people use third-party software like Opt-in Monster, LeadPages, or the List Builder plugin from SumoMe. But while these applications are convenient, they aren’t always the best choice, and as we’ll talk about in this tutorial, they’re easy to replace with jQuery.

Here’s how.

Step 1: Install jQuery

To begin, download and embed a copy of jQuery inside a web page. To save the slightest bit of time, feel free to embed an external copy of jQuery:

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Next, we’ll need to add two different jQuery plugins to our page:

The first plugin is the jQuery Modal plugin. This is what we can use to create the modal box that appears after the user visits our page. When adding the plugin to your project, make sure to download all of the files:

  • jquery.modal.min.js
  • jquery.modal.css
  • close.png
  • spinner.gif

You can follow this tutorial using other modal plugins (or a custom modal), but I’ve found the jQuery Modal plugin to be the simplest option.

The second plugin is the jQuery Cookie plugin. This is what we’ll use to make it so that when a user clicks the “Close” button on the modal, they won’t see the modal again for the next thirty days. This means:

  1. Everyone should see the modal at least once.
  2. Return visitors won’t see the modal on every visit.

Relying on cookies is not a fool-proof approach but it’s good enough.

After setting up jQuery itself, along with these plugins, you should have a HTML file that looks something like this:

<html>
    <head>
        <title>jQuery Demo</title>
        <link rel="stylesheet" href="css/jquery.modal.css">
        <script src="js/jquery.min.js"></script>
        <script src="js/jquery.modal.min.js"></script>
        <script src="js/jquery.cookie.min.js"></script>
    </head>
    <body>
    </body>
</html>

Step 2: Create a Modal

Between the body tags, write the following:

<div id="opt-in" style="display:none;">
    <form>
        <input type="email" placeholder="Your email goes here...">
        <input type="submit" value="Free Instant Access!">
    </form>
</div>

This is our modal. It’s the box that will appear when a user visits the page. It won’t look that marvelous in its current form, but that doesn’t matter. It is, however, worth mentioning a couple of things:

  1. Our modal needs a unique ID for us to reference. In this case, I’ve given the modal an ID of “opt-in”.
  2. We’ve set the display property to “none” so the modal won’t appear within the main interface. It’ll only appear when it’s called.

Beneath this code, right before the closing body tag, write a function that’ll execute once the page loads:

<script type="text/javascript">
$(window).load(function() {
    // code that'll run when the page loads
}
</script>

Then, to make the modal appear when the page loads, we can use a modal function that’s provided to us by the jQuery Modal plugin:

<script type="text/javascript">
$(window).load(function() {
    // make the modal appear
    $('#opt-in').modal();
});
</script>

After saving the file and refreshing the page inside the browser, the modal should appear:

Example Modal

But we don’t want the modal to appear immediately. It’s best if there’s a slight delay after the user visits the page. To achieve this, we can write a setTimeout function, like so:

setTimeout(function() {
    // this code will execute after 7 seconds
}, 7000);

The first argument is the function we want to execute, and the second argument is the delay (in milliseconds).

When combined with the modal, the code will resemble:

$(window).load(function() {
    // delay by 7 seconds
    setTimeout(function(){
        // make the modal appear
        $('#opt-in').modal();
    }, 7000);
});

Step 3: Manage Cookies

When a user clicks on the modal’s “Close” button, we don’t want them to see the modal again for thirty days. This makes the modal far less annoying.

To achieve this, make it so a function executes when a user clicks on the “Close” button. This button can be referenced with the .close-modal class and this function can be placed at the bottom of the load function:

$('.close-modal').click(function(){
    console.log("Modal closed.");
});

So the code should resemble:

$(window).load(function() {
    // delay by 7 seconds
    setTimeout(function(){
        // make the modal appear
        $('#opt-in').modal();
    }, 7000);
    // when the "Close" button is clicked
    $('.close-modal').click(function(){
        console.log("Modal closed.");
    });
});

Then inside this new function, we’ll create a cookie:

$('.close-modal').click(function(){
    // create a cookie
    $.cookie('hideTheModal', 'true');
});

Here, the cookie is named hideTheModal and it contains a value of true. We can also pass through an expires option to define how long the cookie should last:

$('.close-modal').click(function(){
    // create a cookie
    $.cookie('hideTheModal', 'true', { expires: 30 });
});

Something that is important to know though is that Google Chrome doesn’t support cookies for local files. This means you’ll need to test this cookie-based functionality through a browser like Safari or Firefox.

With this cookie in place, we can now write the following conditional:

var hideTheModal = $.cookie('hideTheModal');
if(hideTheModal == null){
    // modal appears
} else {
    // modal doesn't appear
}

So in context, the code should resemble:

$(window).load(function() {
    var hideTheModal = $.cookie('hideTheModal');
    // if the cookie hasn't been set...
    if(hideTheModal == null){
        // delay by 7 seconds
        setTimeout(function(){
            // make the modal appear
            $('#opt-in').modal();
        }, 7000);
        // when the "Close" button is clicked
        $('.close-modal').click(function(){
            // set the cookie
            $.cookie('hideTheModal', 'true', { expires: 30 });
        });
    }
});

Then it’s “just” a matter of designing a better looking modal, and also split-testing different designs to see how they affect the opt-in rate. But of course, those precise topics are beyond the scope of this tutorial.

Conclusion

As we’ve seen, it’s not difficult to create an opt-in modal with jQuery. Whether or not you take this approach will depend on the context — in many cases, it makes more sense to use pre-made software — but especially when I build small or static websites, I appreciate this lightweight and endlessly customizable approach.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • D

    ‘Complaints from a vocal minority’ – think you mean majority.

  • petchy

    $(‘.close-modal’).click(function(){
    // set the cookie
    $.cookie(‘hideTheModal’, ‘true’, { expires: 30 });
    });

    It cannot set cookie. I’ve changed to below

    $(‘#opt-in’).on($.modal.BEFORE_CLOSE, function(event, modal) {

    // set the cookie
    $.cookie(‘hideTheModal’, ‘true’, { expires: 30 }); });

  • martinczerwi

    Nice for a starter. But thank you for pointing to Opt-In-Monster. I like their “Intent to leave”, where the mouse movement is analyzed, to detect a move towards the close buttons. Maybe you could do a follow up on this tut, with the intent on mouse movement demonstrated :)
    (By the way, after opening the disqus sidebar, scrolling your page doesn’t work anymore… have to reload then)

  • Noah Patterson

    I had to move the ‘modal-close’ on click into the timeout function. I suppose this is because JS tries to bind the click event before ‘modal-close’ exists?

  • http://www.wpbeginner.com/ Syed Balkhi

    First of all thank you for using our plugin as a click-bait in your title.

    I’m the co-founder of OptinMonster, and this article doesn’t even get you 10% into cloning OptinMonster.

    All what your tutorial shows is how to create a popup modal box (which is what a title should’ve been). However I’ll take it as a compliment to the popularity of our plugin that now our brand is being used for click-baits.

    Having that said here is why you probably don’t want to follow this tutorial:

    1. The most important aspect of lead-generation forms is analytics. Without that, you’re just shooting arrows in the dark. You don’t have any analytics with this solution. That’s why people choose OptinMonster.

    2. To improve your conversion, you need to run split-tests to see which design and message works. This “clone” doesn’t allow you to do that. That’s why people choose OptinMonster because our solution is easy to use.

    3. Just building a list isn’t important. Segmenting the list in targeted groups is how you increase your open rates, click-through rates, and conversions. This “clone” doesn’t do that. That’s why people choose OptinMonster because we allow you to show targeted popups and other optin-forms based on user’s interests and how they interact with your website.

    4. This solution requires you to have custom HTML forms. Which is great however working with a native API integration with the email providers, like we do often provides seamless integration and a better experience. OptinMonster has 19 integrations and that’s why people use our product.

    5. When a user subscribes, they want to know did it go through? With a normal popup solution, once the user subscribes, it just closes the window. With OptinMonster, we allow you to show success message to the user to improve UX. We also allow you to do success redirect to give users special offers, deliver a free eBook or other promised goods, etc.

    6. OptinMonster comes with Canvas that allows you (the developer) to completely customize everything in it. It’s basically a blank modal box that you can add HTML / CSS in. You can even add WordPress shortcodes to integrate with your eCommerce platform, calendar widget, or basically anything else that you want. That’s why developers choose OptinMonster because of unlimited customization options that are available (without having to worry about handling cookies across several browsers and operating systems — Trust me that’s a nightmare and takes a lot of time which we have perfected over the course of last year).

    And I can go on and on, However the point is, this is a great tutorial to show “How to Create a Modal Popup using jQuery”.

    However the author clearly doesn’t understand the functionality of OptinMonster to suggest that this is a “clone” — this is a mere click-bait.

    Also the author does not understand the value that platforms like OptinMonster, SumoMe, and LeadPages offer (some of which I highlight above) that are crucial for a success lead-generation forms.

    If your goal is to create a simple modal box to show a facebook like box, then by all means use this tutorial. However if you’re serious about lead-generation, then I’d suggest checking out the tools mentioned in the article.

    Lastly, I’m extremely disappointed in the SitePoint editorial for letting this click-bait go live. I used to have a lot of respect for this publication however misguiding users is never a great place to start.

    Hopefully this comment won’t be sensored.

    • https://frenchtogether.com/ Benjamin

      Honestly, I don’t see the problem. They simply use the Optinmonster name because people know your plugin and what it does, and because “Modal Popup using jQuery” is less clear (to me at least).

      I also think you don’t need to show how Optinmonster is superior to this solution. It’s obvious. And I highly doubt Sitepoint intends to steal your customers with this script.

      Reading this post just made me want to buy Optinmonster more (I am waiting for a possible black friday sale).

      • http://www.wpbeginner.com/ Syed Balkhi

        Hi Benjamin,

        I don’t have a problem with them using our product name if they actually offer what the article “claims” to do. If they were creating a real clone, then I’d understand. But this article only cover one little aspect of our product.

        For example there are many sites that talk about: How to Create a Pinterest Like Theme Design… (it doesn’t say how to create a Pinterest Clone). Because Pinterest offers a lot more than the infinite loading view of thumbnails.

        Furthermore, the reason why I commented and highlighted all the ways OptinMonster is better than the basic modal popup that this tutorial shows is because the author wrote this:

        “while these applications are convenient, they aren’t always the best choice..”

        Even though he failed to really give a good reason why they aren’t a best choice.

  • http://www.mancko.com Alexis

    Hi,
    Your tutorial is very neat and easy to understand with all the right steps in it.
    However, can you elaborate a bit about the fact that “Google Chrome doesn’t support cookies for local files”?
    Thanks

  • Say it with a Sock

    Thank you for posting this tut – it is awesome! I have followed your guidelines but I keep getting this console error: Uncaught TypeError: $.cookie is not a function

  • Pasban

    It seems cookie function is no longer available. Although there are some workaround like document.cookie etc.

    However, if user disable the cookie, you will fail to write it again.

    I think the best option is to use localStorage which it is just available for the site and domain itself.

    localStorage.setItem(“status”, ‘closed-once’);

    check w3schools for more information.

  • Scot Nery

    Dude! thank you!

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.