Where do I put the JQuery to dynamically change a link based on a data- attribute?
Hi ... I am a JQuery newbie and could really use some help trying to create a variation. Any help would be greatly appreciated!
I have a variation that includes a link that is not on the Original. I have the button working fine on a per-page basis. The problem is that I want to run my experiment site-wide, and the link needs to change for each page. I can't manually edit the URL for each page, so I need some JQuery way to do it.
The <body> tag of the each page includes a data- attribute: data-action="sample-campaign"
With that attribute, I can generate the URL I need: http://sumofus.org/a/sample-campaign/?sub=link
I think this is some pretty straightforward jQuery:
var el = $('[data-action]'); var str = 'http://sum.org/a/'+el.data("action")+'/?sub=link'; el.html('<a href="' + str + '">' + str + '</a>');
But I am not sure where I am supposed to put this within Optimizely in order for it to run on just one variation, but site-wide. I have read all the documentationn but it isn't clicking for me. Help? Thanks so much!
If you go to that variation in the editor and hit the blue "<edit code>" button on the bottom right, the box where you paste the code will pop up. Then you just hit "Apply" and you're good to go. Hope that helps!
Here's a relevant article from Optimizely: The Code Editor
First, Elisa is right with the "where".
But i'm afraid the code is incomplete, if your body tag looks like <body data-action="...">, then
var el = $('[data-action]');
will select the body tag and
el.html('<a href="' + str + '">' + str + '</a>');
will replace the content of the body tag with a single link.
I don't think you want that.
And whoever told you it's straightforward, don't trust him. ;-)
Thank you so much for this! So ... if this approach won't work, how can I accomplish this?
Here is the context: we are testing a button that will let the user share a link on WhatsApp. I have a button that works, but it requires me to manually enter the link url for every campaign. Now I am ready to run a full site test, but I can't figure out how to dynamically create the link based on the body tag. Any advice woulld be greatly appreciated!
I appreciate the advice! Based on this feedback, I have created a new question with more context about what I am trying to do: https://community.optimizely.com/t5/Developers/JQuery-to-dynamically-change-a-link-inside-a-button/m...
Thanks again for your help!