Dynamic Image Replacement Using URL Parameters

  • 13 September 2017
  • 37 replies
  • 622 views

Userlevel 6
  • Former Unbouncer
  • 198 replies

community tips scripts banner

Similar to Dynamic Image Replacement, this script will allow you to also swap out different images on the page based on a URL parameter.

The code is actually quite simple. By including a image’s source URL as a value of a specific URL parameter you can swap it out with a default image on the page (which has been added via the page builder).

You can see this in action (built in Unbounce) here:
http://unbouncepages.com/image-swap/


🚨
This is not an official Unbounce feature. This functionality is based entirely on third party code, and has only been tested in limited applications. Since this isn’t a supported Unbounce feature, our support team will be unable to assist if things go awry. So if you are not comfortable with HTML, Javascript and CSS, please consider consulting an experienced developer.


Step 1.

Add the script from here:

Step 2.

Add a default image(s) to the page using the image widget in the page builder. Update the script with the ID of the default images on the page you’d like to swap based on a URL parameter.

Step 3.

Decide on a URL parameter you would like to use to pass through the new image URL and update the script in the //Add parameters section.

For example you could assign a parameter of “image” and then format a URL like so:
mydomain.com/page/?image=URL-OF-IMAGE

In this case the code would look like:

>      // Add URL parameters    
>         var img1 = getURLParameter('image');

Step 4.

Create your URL using the source of the image you’d to replace.

PROTIP Use a URL shortener for the image source in the URL to keep is cleaner and shorter

Some Notes:

  1. The dynamic image will keep the same dimensions of the default image added via the builder. So make sure your images are all the same size and resolution to avoid stretching and zooming.
  2. In order to add multiple images simply create more variable in the code for the default images and parameters (the default script has two).

Want to take your Unbounce landing pages + Convertables™ to the next level?
:spinbounce: Check out the Ultimate List of Unbounce Tips, Scripts & Hacks


37 replies

Userlevel 6
Badge +4

Has anyone had any luck getting this script to work lately? I am using the latest iteration posted in the last comment to no avail.

[UPDATE] Brainfart on my end - I can confirm that this works 😅

Userlevel 6

I took another look, and ironically I think the issue was being caused by the setTimeout function that I had added previously to fix an issue with the image loading for someone else.

I made a copy of your page and removed that settTimeout and it appears to have fixed the issue on my copy. Here’s the code:

<script>
(function(){
/*
Unbounce Community :: Tips & Scripts :: Dynamic Image Replacement Using URL Parameters
TS:0002-04-???
***********************
Do not remove this section. It helps our team track useage of external workarounds.
*/
    // Add the image source as the value of a URL parameter to have it appear on the page

    // Add ID's of Images in builder
    var image1 = $("#lp-pom-image-520");
    var image2 = $("#lp-pom-image-12"); 

    // Add URL parameters    
    var img1 = getURLParameter('img1');
    var img2 = getURLParameter('img2'); 

    // function to get URL parameter  
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }

    // change image if parameter exists  
    if (img1) {
    
      $(image1).children().children().attr("src",img1);
      $(image1).children().children().attr("data-src-desktop-1x",img1);
      $(image1).children().children().attr("data-src-desktop-2x",img1);
      $(image1).children().children().attr("data-src-desktop-3x",img1);
      $(image1).children().children().attr("data-src-mobile-1x",img1);
      $(image1).children().children().attr("data-src-mobile-2x",img1);        
      $(image1).children().children().attr("data-src-mobile-3x",img1);
    
    } 
 
    if (img2) {

      $(image2).children().children().attr("src",img2);
      $(image2).children().children().attr("data-src-desktop-1x",img2);
      $(image2).children().children().attr("data-src-desktop-2x",img2);
      $(image2).children().children().attr("data-src-desktop-3x",img2);
      $(image2).children().children().attr("data-src-mobile-1x",img2);         
      $(image2).children().children().attr("data-src-mobile-2x",img2);         
      $(image2).children().children().attr("data-src-mobile-3x",img2); 

    }
})();   
</script>

Also FYI there was another syntax error in the dynamic text swapping script. You’ll want to wrap the text in double quotes (") otherwise the apostrophe’s in the copy will escape the string and cause a syntax error. You’ll want it to look like this in the code editor:

Badge

Good catch @Rob … I made the change, but it’s still not working. Anything else you see?

Userlevel 6

Hi Kristi! Looks like there is a small typo in the code where the variables are being set as “imageOne” and “imageTwo” but then referenced later in the code as “image1” and “image2”, which is causing an uncaught reference error on the page.

If you make sure those variable match in the code I think that should fix your issue 🙂

Badge

Hi @Rob @Hristian @Thomas_GOIRAND1 ,

I’m playing with this again, but I can’t get the updated script to work.

I have Jquery loading in the header, and the rest of the script before body end.

<script>
(function(){
/*
Unbounce Community :: Tips & Scripts :: Dynamic Image Replacement Using URL Parameters
TS:0002-04-???
***********************
Do not remove this section. It helps our team track useage of external workarounds.
*/
    // Add the image source as the value of a URL parameter to have it appear on the page

    // Add ID's of Images in builder
    var imageOne = $("#lp-pom-image-520");
    var imageTwo = $("#lp-pom-image-12"); 

    // Add URL parameters    
    var img1 = getURLParameter('img1');
    var img2 = getURLParameter('img2'); 

    // function to get URL parameter  
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }

    // change image if parameter exists  
    if (img1) {
     setTimeout(function(){
      $(image1).children().children().attr("src",img1);
      $(image1).children().children().attr("data-src-desktop-1x",img1);
      $(image1).children().children().attr("data-src-desktop-2x",img1);
      $(image1).children().children().attr("data-src-desktop-3x",img1);
      $(image1).children().children().attr("data-src-mobile-1x",img1);
      $(image1).children().children().attr("data-src-mobile-2x",img1);        
      $(image1).children().children().attr("data-src-mobile-3x",img1);
     }, 200);
    } 
 
    if (img2) {
     setTimeout(function(){
      $(image2).children().children().attr("src",img2);
      $(image2).children().children().attr("data-src-desktop-1x",img2);
      $(image2).children().children().attr("data-src-desktop-2x",img2);
      $(image2).children().children().attr("data-src-desktop-3x",img2);
      $(image2).children().children().attr("data-src-mobile-1x",img2);         
      $(image2).children().children().attr("data-src-mobile-2x",img2);         
      $(image2).children().children().attr("data-src-mobile-3x",img2); 
     }, 200);
    }
})();   
</script>

Here’s my test page with legit params: https://my.parlor-games.com/survey-results/?score=5&img1=https://parlor-games.s3.us-west-2.amazonaws.com/meter5.png

Any idea what I’m missing?

Thanks in advance for your help!

Kirsti

@Rob / @Hristian Any thoughts? 😕

Hi! @Rob / @Hristian I’ve been trying to implement the Dynamic Image Replacement using URL parameters on this landing page https://lp.laboremedge.com/cp-le-digital-marketing-agency/
However, it looks like the code might not be working anymore or I’m probably missing something here. Any ideas of what the issue could be?

Thank you!

If anyone is interested in here, the issue is the two scripts are meant to be stored in different sections, the jquery library goes in the head and the rest with the function goes in body.

Now working on my end.

Hey @Rob any help here would be very nice! 😀

No luck for me, copied the code with no change and updated the images blocs numbers. Here is a test, maybe I missed something?

Here is a link of a test so you can check if you can:

Userlevel 6

hello @tom_goirand and @Elbert thanks for raising this. I’ve found a bit of time to take a quick look at this and you are correct the original script appears to no longer work. I think I may have figured out a solution though 🙂

I was able to get the images to swap on the example page by wrapping the function that changes the image ‘src’ in a setTimeout function to put a slight delay on changing the images. This appears to have worked in getting the images to swap. On the example I’ve set the length of the delay to 2 milliseconds, so you can briefly see the original before it changes over.

I’m not entirely sure why the code stopped working in the first place be completely honest. Improvements have been made to how we host and serve images in the years since this workaround was first posted, so my best guess is that somewhere along the line a breaking change was introduced that caused this code to stop working. What I think might have happened was that the original javascript code was executing before or around the same time that the image on the page was being served, so the function to swap the images wasn’t being executed properly (you can’t swap what isn’t there!). Introducing the slight delay looks to have fixed the issue as it give time for the original image to load and then swap it with the image in the URL param.

I’ve updated the code in the Github gist with the setTimeout function, so you should be all set to copy from there now. I hope it gets it working for ya!

Nope dead end I guess…

Ditto, not working over here either. Any ideas @Rob ? Or did you work it out @Thomas_GOIRAND1 @Jonathan_Solnicki ?

Hi Rob, I just tried this feature with no success… It turns out it looks dead so far (even the example: http://unbouncepages.com/image-swap/?img1=http://i.imgur.com/hmDg3uC.jpg is not working). Do you confirm?

Hello, this is a random question, but can I use this code for Wordpress?

Hey, I’ve been trying to get this to work but have had no luck.

The sample page in the original post doesn’t even work for me on chrome even in an incognito window…

Can anyone help?

Thanks

Has anyone had any issues with dynamic images on mobile? My images look great on desktop but do not get scaled down when viewing them on mobile.

Userlevel 6

Thanks for catching that @kirstihegg! That example page is quite old and was definitely in need of an update (Imgur also has since restricted the ability to embed an image). I did a quick update to the page to remove the reference to Dropbox and Imgur so others won’t run into the same issue.

Glad you were able to get it to work in the end!

Badge

Thank you! Switched to my AWS account. However, @Rob’s sample page says at the bottom that dropbox and google drive can both be used for hosting images. Might want to update that…

Userlevel 7
Badge +3

Hi @kirstihegg,

You’ll need to host the images on a web server you control. Dropbox doesn’t allow embedding of images on 3rd parties.

Best,

Badge

@Rob or @Hristian I’m trying to implement this on the following page: https://my.caredetective.com/test-image-swap/

You can see that I have a laptop image at the top, and i want to replace it with this image: https://www.dropbox.com/s/09a57shyrzozbjr/slide1.jpg

When I enter the URL: https://my.caredetective.com/test-image-swap/?img1=https://www.dropbox.com/s/09a57shyrzozbjr/slide1.jpg the original image disappears, but is not successfully replaced with the image in the URL.

I’ve checked and double checked… and it’s driving me crazy! Any ideas?

Thanks in advance!

Userlevel 6

Hi @jerry12 This actually wouldn’t be too difficult. What you can do to achieve this is to set the image URL as a separate variable in the code and also add the image name as a variable to check if the parameter in the URL matches the name you’ve specified in the code. If it does, then set the image “src” to the URL you’ve hardcoded into the script.

Keep in mind though that this wouldn’t be “dynamic” so to speak as it would involve hardcoding the image URL in the script. That’s not necessarily a bad thing though, as it will give you full control over what’s shown on the page. If the parameter value doesn’t match what’s in the URL then the original image the page is published with will show, so there isn’t a huge risk involved if someone does land on the page with a URL that contains a different parameter value than what’s been set in the code. This would be good to use if you only had one alternate image to show people, as there would be no need to have it be fully dynamic.

Here’s an example

<script>
(function(){
/*
Unbounce Community :: Tips & Scripts :: Dynamic Image Replacement Using URL Parameters
TS:0002-04-???
***********************
Do not remove this section. It helps our team track useage of external workarounds.
*/
    // Add the image source as the value of a URL parameter to have it appear on the page
    // Add ID's of Images in builder
    var imageOne = $("#lp-pom-image-11");

    // Add URL parameters    
    var img1 = getURLParameter('img1');

    // Add paramater value
    var paramVal = "image.jpg"

    // Add image URL
    var imgUrl = "https://example.com/image1"


    // function to get URL parameter  
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }

    // change if image url parameter value matches
    if (img1 == paramVal) {
      $(image1).children().children().attr("src",imgUrl);
      $(image1).children().children().attr("data-src-desktop-1x",imgUrl);
      $(image1).children().children().attr("data-src-desktop-2x",imgUrl);
      $(image1).children().children().attr("data-src-desktop-3x",imgUrl);
      $(image1).children().children().attr("data-src-mobile-1x",imgUrl);
      $(image1).children().children().attr("data-src-mobile-2x",imgUrl);        
      $(image1).children().children().attr("data-src-mobile-3x",imgUrl);        
    } 

})();   
</script>

With the above, if you sent someone to the page with the URL www.example.com?img1=image.jpg then the image would swap out. Hope this helps! Let me know if you get stuck anywhere

How can I specify the image URL within the code so I only call the image name “image.jpg” instead of the whole URL?

Thanks!

Userlevel 5
Badge +4

Hello,

thanks for this script but be careful there is a mistake in the last update.

At the beginning you write : var imageOne = $("#lp-pom-image-11");

but a the end you write : $(image1).children().children().attr(“src”,img1);

it should be the same everywhere.

Also, i’ve noticed that the Bitly links have to be https if your LP is securised.

Userlevel 6

Hi @Scott_Fahy thanks for the heads up and pointing this out (apologies it took me so long to get to this). You are absolutely correct, the issue with this code was related to Unbounce rolling out native support for retina images. As @GregorySR pointed out the problem was that Unbounce is now using srcset to serve up the retina images and this workaround wasn’t created with that in mind.

Thanks so much GregorySR for figuring this out and for finding the solution (huge props!!). As he mentioned the best fix for this is to just change all those attributes to the same URL. Could use a refactor, but this will work in a pinch. To fully understand the cause of the issue it helps to understand how srcset works. Basically when an image is retina Unbounce will serve all the versions when the page load, the browser then determines the quality of the image to serve based on the screen resolution that’s viewing the page. This is the reason there are all those “data-src-_______" attributes for each image. I’ve updated the gist that contains the original code for the workaround (can be found here or linked at the top of the post). For anyone who doesn’t want to scroll or click a link, here’s an example of what the updates look like to get this working:

if (img1) {
      $(image1).children().children().attr("src",img1);
      $(image1).children().children().attr("data-src-desktop-1x",img1);
      $(image1).children().children().attr("data-src-desktop-2x",img1);
      $(image1).children().children().attr("data-src-desktop-3x",img1);
      $(image1).children().children().attr("data-src-mobile-1x",img1);
      $(image1).children().children().attr("data-src-mobile-2x",img1);        
      $(image1).children().children().attr("data-src-mobile-3x",img1);        
    } 

Thanks again to everyone who figured this out!!

Reply