To allow more flexible use cases outside of some of the existing features, some of the elements that come with ZionExtras have their own JS events that allow you to trigger other things.
Some example use cases;
- You want to trigger something at the very moment that the lightbox is opened.
- You want to trigger something when an offcanvas is closed.
- You want something to occur when the countdown timer has finished.
- etc
Using JS Events
For a brief introduction to using events in JS. You’ve probably come across the most common events such as ‘click’, or ‘scroll’ which happen when the user clicks a specific element or scrolls the page.
For eg the way we do something when an element is clicked (using jQuery for simplicity), is to do this..
jQuery(document).ready(function($) {
$( "#myelement" ).on( "click", function() {
// do something
});
});
Where “click” here is the event being listened for on the element with the ID ‘#myelement’. The ‘do something’ code will only run when that event is triggered, ie when the user clicks.
Simply replace ‘click’ with the event of your choice to listen out for.
Many plugins have their own events to listen for, eg Woocommerce has the ‘added_to_cart’ event for when users have added a new item to the cart.
ZionExtras Events
We’ve added our own events to some of the elements to listen for. More will be added to elements that have some type of user interaction and where it makes sense to add them. Currently, as of ZionExtras v1.0.3+, these are included..
x-offcanvas:opened – When the off-canvas is opened
x-offcanvas:closed – When the off-canvas is closed
x-lightbox:visible – Just as the lightbox is made visible
x-readmore:expand – Just as the link is clicked to expand
x-readmore:expanded – As the element finishes expanding
x-readmore:collapse – As the link is clicked to start collapsing
x-readmore:collapsed – As the element finishes collapsing
Example code snippet
Let’s say we want an element to appear on the page the moment a particular off-canvas closes. If the off-canvas has an ID #myoffcanvas and we’re hiding an element on the page with the ID #myhiddenelement, then the code to make this hidden element show when the offcanvas is closed would look like this..
jQuery(document).ready(function($) {
// listen for the closing of the offcanvas with ID '#myoffcanvas'
$( "#myoffcanvas" ).on( "x-offcanvas:closed", function() {
//code to run
//show the hidden element on the page
$('#myhiddenelement').show();
});
});
That’s it
Obviously, the code that runs inside the function when the event is triggered is where your custom code would go, but hopefully this gives you a good idea of how you’d use these events if you’re needing to trigger something of your own.