Vanilla JavaScript Button Toggler

Introduction

This is a prototype I'm working on to simplify setting up button functionality. The goals are:

The Demo

Here's the HTML code and demo buttons

HTML Source

<div class="demo_area">

    <button 
        class="demo_button" 
        data-name="Alfa"
        data-toggle_text="Alfa On"
        >Alfa Off</button>

    <button 
        class="demo_button" 
        data-name="Bravo"
        data-toggle_text="Bravo On"
        >Bravo Off</button>

    <div class="demo_status">No button clicks yet</div>

</div>
Output
No button clicks yet

Initial Functions

The first step is to set up the on/off functions

JavaScript

function on_demo_function(element) {
    const status_elements = document.querySelectorAll(".demo_status")
    status_elements.forEach((status_element) => {
        status_element.innerHTML = `${element.dataset.name} clicked on`
    })
}

JavaScript

function off_demo_function(element) {
    const status_elements = document.querySelectorAll(".demo_status")
    status_elements.forEach((status_element) => {
        status_element.innerHTML = `${element.dataset.name} clicked off`
    })
}

The Main Adder

Here's the function that does all the work

JavaScript

function add_toggle_function_to_button_selector_demo(on_function, off_function, selector) {
  let elements = document.querySelectorAll(selector)
  elements.forEach((element) => {
    element.addEventListener("click", (event) => { 
        elements.forEach((update_element) => {
            update_element.classList.toggle("on")
            update_element.classList.toggle("off")
            const text_buffer = update_element.innerHTML
            update_element.innerHTML = update_element.dataset.toggle_text
            update_element.dataset.toggle_text = text_buffer
        })
      const element = event.target
      if (element.classList.contains("on")) {
        on_function.call(undefined, element)
      } else {
        off_function.call(undefined, element)
      }
    })
  })
}

Putting It In Place

With those three functions in place adding the on/off functions to a button (or collection of buttons with the same selector) is done like this:

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  add_toggle_function_to_button_selector_demo(
    on_demo_function, 
    off_demo_function, 
    ".demo_button"
  )
})

Another Look

And here's another batch of buttons that's wired up and working

HTML Source

<div class="demo_area">

    <button 
        class="demo_button" 
        data-name="Charlie"
        data-toggle_text="Charlie On"
        >Charlie Off</button>

    <button 
        class="demo_button" 
        data-name="Delta"
        data-toggle_text="Delta On"
        >Delta Off</button>

    <div class="demo_status">No button clicks yet</div>

</div>
Output
No button clicks yet

Outro

This is working as expected on a mac in safar, chrome, and firefox. Still need to do a little more testing, but so far so good.