How to Run Separate Scripts on Mobile and Desktop

Follow

Some scripts work well on desktop but not on mobile. For example, a sticky header that follows visitors down the page can take up too much of a phone screen. This snippet lets you run code only on desktop, only on mobile, or different code on each.

Screen Shot 2015-11-23 at 2:22:34 PM

This is community code, not an official Unbounce feature. Unbounce Support can't troubleshoot custom code. Test it on a published page before relying on it, and work with a developer if you aren't comfortable editing JavaScript.

Add the snippet to your page

  1. Copy the following snippet:
<script>
if ( lp.jQuery(window).width() <= 600 ) {
// Your mobile code goes here
}else{
// Your desktop code goes here
}
</script>
  1. Open the JavaScripts section and add a new script.

    Unbounce editor showing the Javascripts panel dropdown menu with "Add New Javascript" option highlighted.

  2. Paste the snippet, set the placement to Before Body End Tag, and give the script a clear name so you and Unbounce Support can identify it later. Placement matters, since it controls where the script runs in relation to the rest of the page and keeps it from interfering with other scripts.

    Unbounce Manage Scripts panel showing a Desktop/Mobile code script with jQuery width detection conditional logic.

  3. Paste the code you want to target into the matching section. For example, to run a sticky header script on desktop and tablet only, paste it where the snippet says // Your desktop code goes here. Remove the opening and closing script tags from the code you paste in, since the snippet already has them.

    Screen Shot 2015-11-23 at 2.31.24 PM

  4. Save and republish the page.
  5. Check the page in Preview, or on a computer and a phone, to confirm each version behaves as expected. In this example, the header scrolls with the page on desktop and stays static on mobile.

    Side-by-side preview of a desktop and mobile "Get Your Free Proposal" form layout in Unbounce.

The snippet treats screens 600 pixels wide or narrower as mobile. You can use it any time a page needs to behave differently on mobile and desktop.