Jump to main content

Alert

Enhanced with some modern Javascript, the alert is 'content aware', in that it only displays if the website author has added content via the built-in short text element. The rest of the time, the alert box remains hidden. So it's a practical solution for displaying prominent messages at important times. I wrote some additional Javascript code to keep the alert hidden (using localStorage) if a website visitor dismisses it. If you don't want it dismissible, then just delete the close button and edit the Javascript code accordingly. This example puts the alert in the normal page flow (which I personally prefer), but you could attach it to the top of the page using some fixed or sticky positioning, if you choose to.

Example

HTML & PHP

<div id="my_alert" role="alert" data-alert-box>
  <?php webyep_shortText("Alert Box", false, 550, 240); // WebYepV2 ?>
  <button
    type="button"
    aria-label="Close"
    data-alert-box-dismiss
  ></button>
</div>

CSS

#my_alert {
    display: none;
    position: relative;
    color: #842029;
    background-color: #f8d7da;
    border: 1px solid #f5c2c7;
    border-radius: 0.375rem;
    padding: 1.5rem 3rem 1.5rem 1.5rem;
}

#my_alert.show-message {
    display: block;
}

#my_alert button {
    position: absolute;
    right: 0.75rem;
    top: 0.75rem;
    border: none;
    width: 1.5rem;
    height: 1.5rem;
    line-height: 1;
    opacity: 0.5;
    padding: 1.25rem;
    margin: 0;
    background: none;
    transition: opacity 100ms;
    cursor: pointer;
}

#my_alert button:hover {
    opacity: 1;
}

#my_alert button:before,
#my_alert button:after {
    position: absolute;
    left: 1.25rem;
    top: 0.40rem;
    content: ' ';
    height: 1.75rem;
    width: 2px;
    background-color: #333;
}

#my_alert button:before {
    transform: rotate(45deg);
}

#my_alert button:after {
    transform: rotate(-45deg);
}

Javascript

const alertBox = document.querySelector('[data-alert-box]');
if (alertBox.innerText) {
    alertBox.classList.add('show-message');
}

// This following code is for dismissing the alert box. Delete if not required.
const dismissBtn = alertBox.querySelector('[data-alert-box-dismiss]');
const gotClosed = localStorage.getItem('alert-box');
if (dismissBtn) {
    dismissBtn.addEventListener('click', (e) => {
        e.preventDefault();
        dismissBtn.parentElement.classList.remove('show-message');
        localStorage.setItem('alert-box', 'closed');
    });
}
if (gotClosed && gotClosed == 'closed') {
    alertBox.classList.remove('show-message');
}
// End of dismissing code