How can I handle the onClick function of a button in Webflow to fill the background color of a newly created div block using JS code?

TL;DR
  • Add a button in Webflow with a unique ID.  
  • Use a custom embed to add JavaScript that runs after DOMContentLoaded; on button click, create and style a new div with a set background color, then append it to the page.

To handle an onClick function in Webflow that fills the background color of a newly created div block using JavaScript, follow these steps.

1. Create the Button in Webflow

  • Add a Button element using the Webflow Designer.
  • Give it a unique ID (e.g., create-div-button) via the Element Settings panel.

2. Add a Custom Embed or Code Block

  • Place a Custom code embed either in the Page Settings ➝ Before </body> tag custom code section, or use an Embed element.
  • Make sure your script runs after the DOM is loaded.

3. Write the JavaScript Code

  • Use the button’s click event to create a new <div> and set its background color.

Example:

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const button = document.getElementById('create-div-button');

    button.addEventListener('click', function () {
      const newDiv = document.createElement('div');
      newDiv.style.width = '200px';
      newDiv.style.height = '200px';
      newDiv.style.backgroundColor = '#3498db'; // Blue color
      newDiv.style.marginTop = '20px';

      document.body.appendChild(newDiv);
    });
  });
</script>

  • This script waits for the page to load, then attaches a click event to the button.
  • When clicked, it creates a <div> element, applies a fixed background color, and appends it to the <body>.

4. Publish or Preview the Site

  • Click Publish and test the interaction in your browser.
  • Each button click will add a new div with the specified background color.

Summary

Add a unique ID to your button in Webflow, then use JavaScript via a custom embed to create and style a new div on click. Make sure all scripts are run after DOMContentLoaded to ensure elements are available for manipulation.

Rate this answer

Other Webflow Questions