Streaming live at 10am (PST)

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.

1 Like

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

1 Like

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?