Custom JS not working | Swap SRC

Hi,

I’m trying to add some custom JS that swaps an image src depending on the referrer. I think the code is correct and I’ve added it to the customizer. However, it’s not working. I am wondering if there is some issue with how I am inserting it, or it working with X. Any suggestions would be greatly appreciated. Thanks.

The code is:

if (!/facebook\.com/.test(document.referrer)) {
 document.getElementById('staffImage').src = 'https://treehouserecovery.com/wp- 
content/uploads/2018/03/Justin-mcmillen-founder-ceo-tree-house-recovery.jpg';
 } else{
document.getElementById('staffImage').src = 'http://treehouserecovery.com/wp-content/uploads/2018/03/andrew- 
schneider-medical-director-tree-house-recovery.jpg';
}

Hi There,

Please update your code with this:

if (!/facebook\.com/.test(document.referrer)) {
	jQuery('#staffImage img').attr('src', 'https://treehouserecovery.com/wp-content/uploads/2018/03/Justin-mcmillen-founder-ceo-tree-house-recovery.jpg');
} else{
	jQuery('#staffImage img').attr('src', 'http://treehouserecovery.com/wp-content/uploads/2018/03/andrew-schneider-medical-director-tree-house-recovery.jpg');
}

Let us know how it goes!

Thanks so much for the reply!

  1. Does that mean that custom JS on X needs to be Jquery?

  2. The swap is now working, but the conditional logic isn’t. The image is swapping no matter the refferer. Any idea waht’s wrong? Maybe there is something wrong with this line: if (!/facebook.com/.test(document.referrer)) ? I want the image to swap only if facebook is the referer.

Thanks SO much!!!

The image is wrapped with an <a> tag so the '#staffImage img' will not work with the document.getElementById. We have to use the jQuery.

Please try updating your code with this:

if (document.referrer.indexOf('facebook.com') >= 0) {
	jQuery('#staffImage img').attr('src', 'https://treehouserecovery.com/wp-content/uploads/2018/03/Justin-mcmillen-founder-ceo-tree-house-recovery.jpg');
}

Let us know how it goes!

That worked! Thank you SO MUCH! I know this is bordering on outside the scope of support, so, again, I really appreciate it!

One more questions:

I am trying to do the same thing on another page, but with a background image. It doesn’t seem to be working. It is switching out images that are on top of the background Image. Any idea how I can make this work? The page is in the secure note.

Thanks again!

You can try with this code:

jQuery('#BgImg').css('background-image', 'url(http://treehouserecovery.com/wp-content/uploads/2017/08/fitness-healthy-men-gym.jpg)');

Hope it helps :slight_smile:

Amazing! Thanks again! I really appreciate it!

1 Like