Jump to main content

Data

Sometimes a need arises to collect data from a website author, but keep it hidden on the page. HTML data-* attributes are perfect for this task. They act like little storage containers, which can be attached to any element and used to store useful data. Such data can include strings, booleans and numbers. Highly useful for cleaning up the editing interface, hiding complicated code from website authors and making data available for Javascript to use in countless possible ways. Using a combination of conditionals and a short text element, it becomes feasible to let authors add data, then switch elements back to their normal state when the edits are done.

Example

Click the button below to run some Javascript. This Javascript code will take a number (the number '16') from the hidden data attribute on the button and concatenates it into some alert text.

HTML & PHP

<?php if(webyep_bIsEditMode() == false) : ?><button data-stock="<?php endif; ?><?php webyep_shortText("Number Box", false, 550, 240); // WebYepV2 ?><?php if(webyep_bIsEditMode() == false) : ?>" class="btn">Stock Checker</button><?php endif; ?>

CSS

Javascript

const theButton = document.querySelector('[data-stock]');
const inventory = theButton.dataset.stock;

theButton.addEventListener('click', () => {
    alert(`We currently have ${inventory} rebuild kits available in stock.`);
});