Notice Bar using Alpine.js and Tailwind CSS
I'm working on my Craft CMS starter package and expanding what it has baked in out of the box. I'm planning on adding in several features or components that are common across most sites. The first one I've added is a notice bar.
This is quite simple to do with AlpineJS. It uses 2 first party Alpine JS plugins Collapse and Persist. The collapse plugin makes for a smooth hide animation when closing the notice bar.
In Craft I have an entry with three fields Text
(redactor), Button
(link field) and Notice Bar Location
(select field). The text field is for copy, the button for a button and the location field sets whether the notice bar should appear on the homepage only or on all pages.
Here is the complete code.
{% set notice = craft.entries.section('noticeBar').one() %}
{% if notice.enableNoticeBar == '1'
and ( notice.noticeBarLocation !="homePageOnly" or ( entry.slug == '__home__' ) )
%}
<div x-data="{ expanded: $persist(true).as('notice-bar').using(sessionStorage) }">
<div
class="shadow-inner drop-shadow bg-gradient-to-b from-gray-100 via-gray-50 to-gray-100"
x-show="expanded"
x-collapse.duration.300ms >
<div class="container">
<div class="relative flex flex-row items-center w-full mx-auto lg:w-5/6">
<div class="py-4 grow">
{{ notice.text|retcon([
['attr', 'p', { class: 'm-0 text-sm' }]
]) }}
</div>
{% if notice.button|length %}
{{ notice.button.getLink({
class: 'btn mx-8',
}) }}
{% endif %}
<button
class="absolute text-xs font-bold text-red-400 top-1 right-2"
@click="expanded = ! expanded"
aria-label="Close">
X
</button>
</div><!-- /.w-full flex flex-row -->
</div><!-- /.container -->
</div>
</div>
{% endif %}
Originally I was going to set a cookie when the notice was closed and not display the notice again until the cookie expired. However it was simpler to use the AlpineJs persist plugin and set the persist state to use session storage so that the notice bar does display via the current session but will display on the next visit.
x-data="{ expanded: $persist(true).as('notice-bar').using(sessionStorage) }"
In the above x-data I've added the .as('notice-bar')
custom key so that if I use persist anywhere else it will be a unique instance.