How do I add javascript or jquery script to a button or text in Webflow

I have created a modal and I want to stop the Youtube video from playing in the background when the modal is closed. How do I add the code to a button or text? If you check on my site, I have a Link Text that I want to add the embedded code too, but it is not working?

You can find this helpful:

I need to do the same, but this article is not helpful at all.
The question is how to attach onClick attribute to link or button.

2 Likes

I would simply add an id to your button within the Webflow UI, then target that button with javascript custom code by adding a ā€œclickā€ event listener which would then run whatever function you like.

HTML

<button id="button">button</button>

JavaScript

(function clickMe() {
  const button = document.getElementById("button");
  button.addEventListener("click", event => {
    // šŸ§  your onClick script...
    alert("button clicked");
  });
})();

Codepen here

3 Likes

It works perfectly. Great thanks, Anthony!

1 Like

Im trying to use this method to obfiscate (=confuse) email searching spam bots.
So the user should click on the button and it generates the emailaddress and executes the mailto: method. Trouble is, its displaying the mailto:info@test.com on a new page. Clicking that will call the mail client up buit I need/want to have it go straight to the client.
This is what I have:
I gave my button an ID and put this code on the page

 <script type="text/javascript">
(function clickMe() {
  const button = document.getElementById("HumanContactButton");
  button.addEventListener("click", event => {
    // šŸ§  your onClick script...
    <!-- Begin
user = "info";
domain = "mysite.com";
document.write('E-mail: <a href=\"mailto:' + user + '@' + domain + '\">' + 
			user + '@' + domain + '</a>');
// End -->
   // alert("button clicked");
  });
})();
</script>
1 Like

Since jQuery registers globally, you can use it within any other script file you import after jQuery. Example is a javascript UI. If you import a script file before jQuery, jQuery will not be available at load, but it will be available inside functions called after jQuery has been loaded.

Might be the most stupid question but: How do I give Buttons an ID?

Hi Anthony, any chance of re-publishing of your code pen here.
Cheers, Ru

sure, there you go: https://codepen.io/anthonysalamin/pen/LYpJjBW

Great thanks!
I have had a look at this and my basic JS skills have failed me.
I canā€™t work out the syntax to now input the JS (below) to play my video into your eventListenerā€¦

  var vid = document.getElementById("video-animation"); 
  function playVid() { 
  vid.play(); 

I have also published a codepen which shows the HTML for the video with a simple button and have commented out the above JS in between the eventListenerā€™s brackets.

Any help would be massively appreciatedā€¦I am also interested if you could use the custom attribute of the button to execute this (but understanding this is for another day)
:+1:

Hi @kohru,

You donā€™t need to add another function within the click eventListener, simply add your play() method. I would also execute the function once the DOM has finished loading. Right now, you are loading a video from your Google Drive which is relatively slow on my end. Once the video has loaded, your ā€œplay clickā€ function is ready.

Here is the updated codepen

Here is the updated javascript you could use:

// šŸ§  on DOM ready, execute playVideo function
document.addEventListener("DOMContentLoaded", () => {
  playVideo();
});

// šŸ§  playVideo function definition
function playVideo() {
  const button = document.getElementById("btn"),
    video = document.getElementById("video");
  // šŸ§  click event listener
  button.addEventListener("click", () => {
    video.play();
  });
}

thanks for this @anthonysalamin that does make more sense and I like the on the DOM ready function. Your codepen updated link is producing a 404ā€¦could you relink/publish for me. Slowly learning JS which is exciting but also quite mind-boggling!
Thanks for lending your ninja skills!

There you go:
https://codepen.io/anthonysalamin/pen/pojQrKO
Feel free to fork the codepen, as this one is only temporary and will be deleted soon.

1 Like

Great. Super helpful, cheers.

1 Like

I have a similar situation, where Iā€™m attempting to add javascript to a button that launches a modal window. Iā€™ve given it a solid effort based on the advice from this thread, but donā€™t speak proficiently enough in javascript to be able to fully understand how to customize the code provided by @anthonysalamin to my situation.

Iā€™m including a read-only link to the project and will briefly explain what Iā€™m attempting to do, in case anyone has a moment to look into this. I suspect itā€™s an easy integration for someone with more competency than myself.

When clicking any of the buttons at the top of the page (reserve a spot, get involved, get in touch) the desired action is to launch a modal window with an embedded VideoAsk widget. Hereā€™s some code that I found that someone wrote for this very function.

Iā€™ve added the this script to the
<script src="https://www.videoask.it/embed/embed.js"></script>

Iā€™ve added this script to the

But Iā€™m not sure how to add the following javascript to the link in the Webflow editor since thereā€™s no way (that Iā€™ve found) to actually edit the raw HTML

<a href="javascript:void(videoask.loadModal({url: 'https://www.videoask.com/fn5pz0q1v', options: { modalType: 'Fullscreen'}}))">
    Click this link to show the fullscreen modal
  </a> 

https://preview.webflow.com/preview/hope1111?utm_medium=preview_link&utm_source=designer&utm_content=hope1111&preview=3b9010bcdd1626a9ae70d777c0e2ee0e&mode=preview

@Devin_Lyttle sure, I had a quick look and neither did I understand the codepen you provided so I rewrote it quickly from scratch. All you need to do is add a custom data attribute ā€œdata-urlā€ and provide your videoask video ID. The JavaScript snipet will then listen on button click and get that id to inject it into the modal constructor.

Here is the quick codepen for you.
Here is a quick screenrecording I did.

HTML

<a class="button" data-url="fn5pz0q1v" href="">
  reserve a spot
</a>
<a class="button" data-url="fn5pz0q1v" href="">
  get involved
</a>
<a class="button" data-url="fn5pz0q1v" href="">
  get in touch
</a>

<!-- videoask API -->
<script src="https://www.videoask.it/embed/embed.js"></script>

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  // globals
  const log = console.log,
    fullscreen = false, // set to true if you want fullscreen modal
    buttons = document.getElementsByClassName("button"),
    domain = "https://www.videoask.com/";

  Array.from(buttons).forEach((button) => {
    button.addEventListener("click", (event) => {
      event.preventDefault();
      const id = button.dataset.url;
      log(id);
      videoask.loadModal({
        url: `${domain}${id}`,
        options: {
          modalType: fullscreen ? "Fullscreen" : "Side"
        } // end options
      }); // end videoask.loadmodal
    }); // end click listener
  }); // end Array.from
}); // end DOM

Hope that helps

2 Likes

Youā€™re a legend @anthonysalamin - really appreciate you taking the time to look into this! However, Iā€™m afraid you give me far too much credit that I actually know what Iā€™m doing with this code :wink:

In the Webflow editor I see two options for custom code: ā€˜Inside tagā€™ and ā€˜Before tagā€™. Iā€™ve tried adding the code to both sections and assigned a ā€˜data-urlā€™ value of ā€œfn5pz0q1vā€ to each button (which Iā€™m assuming is what I would replace to have it load the correct video?), yet it doesnā€™t seem to want to launch the modal. I thought it had something to do with the class name, since the links Iā€™m launching the model from donā€™t have a ā€œbuttonā€ class; so I tried changing it to ā€˜getElementByIdā€™ instead, so I could target the specific links, but still no luck. Iā€™m not seeing anything else obvious, so Iā€™m assuming that I just have the code entered into the wrong place.

No worries, yes you just forgot to wrap the javascript code inside its <script> tags :slight_smile: Just copy the following code and paste it in the ā€œbefore the end of the body tagā€ custom code section, not in the head custom code section.

<!-- videoask API -->
<script src="https://www.videoask.it/embed/embed.js"></script>

<!-- videoask snipet -->
<script>
document.addEventListener("DOMContentLoaded", () => {
  // globals
  const log = console.log,
    fullscreen = false, // set to true if you want fullscreen modal
    buttons = document.getElementsByClassName("button"),
    domain = "https://www.videoask.com/";

  Array.from(buttons).forEach((button) => {
    button.addEventListener("click", (event) => {
      event.preventDefault();
      const id = button.dataset.url;
      log(id);
      videoask.loadModal({
        url: `${domain}${id}`,
        options: {
          modalType: fullscreen ? "Fullscreen" : "Side"
        } // end options
      }); // end videoask.loadmodal
    }); // end click listener
  }); // end Array.from
}); // end DOM
</script>

as for the classes, simply replace the ā€œbuttonā€ class in the javascript snipet by whateber class you use in webflow. That should do the trick.

1 Like

Amazing, thanks! Got it working, but am having an issue now where all classes with that name (link-with-arrow) are launching a modal. I tried reverting back to using ā€˜document.getElementById(ā€œsupportā€)ā€™ but that doesnā€™t seem to be working. Is there another way that you would recommend handling this?