Webflow sync, pageviews & more.
NEW

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 and a div in Webflow, assigning each a unique ID (e.g., fill-btn and color-div).
  • Insert JavaScript into the page’s custom code section before the closing </body> tag to listen for the button click and change the div’s background color.

To handle an onClick function in Webflow that fills the background color of a new div using JavaScript, you need to use a custom script with event listeners and DOM manipulation.

1. Add the Button and Empty Div in Webflow

  • Use the Webflow Designer to add a Button (e.g., name it Fill Color Button with a unique ID like fill-btn).
  • Add a Div Block to your page and assign it a class (e.g., color-target) or a unique ID (e.g., color-div) if it doesn’t already exist.

2. Add a Unique ID or Class to Elements

  • Select the Button, go to the Settings panel, and set an ID like fill-btn.
  • Select the Div Block and assign an ID like color-div or a class you can target.

3. Add the Custom JavaScript

  • Go to Page Settings (for your current page) or the Custom Code section under Project Settings.
  • Insert the following code in the Before tag section to capture the button click:
<script>  document.addEventListener("DOMContentLoaded", function () {    const button = document.getElementById("fill-btn");    const targetDiv = document.getElementById("color-div");    button.addEventListener("click", function () {      if (targetDiv) {        targetDiv.style.backgroundColor = "#3498db"; // change to any color      }    });  });</script>

Notes

  • Ensure the IDs match exactly (ID is case-sensitive).
  • You can also use document.querySelector(".color-target") if you're using a class instead of an ID.
  • Choose any valid CSS color (e.g., #3498db, red, rgb(0, 255, 0)).

Summary

Add a button and target div in Webflow, assign unique IDs, and use a custom JavaScript snippet to fill the div’s background color when the button is clicked. Add the code in the page’s custom code section before the closing </body> tag for it to work correctly.

Rate this answer

Other Webflow Questions