Click Events

Ignition comes with simple click events you can add anywhere at anytime. They are very powerful and allow you to add classes even to other elements. The toggle switches receive some aria support. You can also run your own callback function after the toggled event is over to do additional custom work.

Data-toggle

To get started, let’s create a simple toggle event. To do so you just need to add a data-toggle to an element like so:

<a class="button" href="javascript:;" data-toggle>Click Me!</a>

Above is an anchor element set to go nowhere. However there is a click event enabled! When you click it, it will add the class toggled-on.

Check it out by clicking preview.

Toggle another class

You can add another class to the element too. Just give data-toggle a value, like so:

<a class="button" href="javascript:;" data-toggle="hello">Click Me!</a>

This will add two classes. The classes “toggled-on” and “hello” will be added to the clicked element. View the inspector to see the change.

Data-Target

You can have toggled-on added to another element, or even that extra class. Just add data-target as another attribute. You can place any selector or selectors separated with commas, into that attribute and all those elements will get the class toggled!

<a class="button" href="javascript:;" data-toggle="highlight" data-target="h2">Click Me!</a>

The above would add class “highlight” to every H2 on this page.

Add AfterToggle Event

Ignition also includes a way to do more once the click event is over. Just use the “afterToggle” event listener on the element. This cannot be done inline for security reasons. Instead use javascript to create an event listener. It will run once the element has been toggled and you can add more to the element, sort of like a callback function.

let el = document.querySelector('.some-element');
el.addEventListener('afterToggle', function(e){
 //do something after the item has been toggled.
}

You will probably want to check if the element has class toggled-on or not and then do whatever you want to the element. Let’s do a quick example.

<a href="javascript:;" class="button demo-after-toggle" data-toggle>Click Me!</a>

<script>
    const demoAfterToggle = document.querySelector('.demo-after-toggle');

    demoAfterToggle.addEventListener('afterToggle', function (e) {

        let toggle = e.target.classList.contains('toggled-on');

        if (toggle) {
            e.target.innerHTML = "I've Been Clicked!";
        } else {
            e.target.innerHTML = "Click Me!";
        }
    });
</script>

As you can see toggle events are easy and pretty cool with Ignition. So use it and abuse it.