Reputation: 21
Hope you can assist, I am trying to make a toggle button with javascript and tailwindcss. I was wondering if my javascript is proper, this way, as I have to write a else statement to get it working and I am not sure if that is required with a toggle button. Please see my html and javascript.
The date-picker-container class is the button, which needs to open the dates container on click of date-picker-container.
<div class="col-start-4 col-end-7 ... bg-slate-500">
<div class="mb-6"> <!-- Date and Time Part -->
Date
<div class="date-time-container">
<div class="date-picker-container relative max-w-xs h-16 bg-red-400 cursor-pointer select-none">
<div class="selected-date w-full h-16 text-center flex items-center">16/7/2023</div>
<div class="dates-container bg-lime-600 absolute w-full top-16 left-0 invisible">
<div class="month flex justify-between">
<div class="arrows prev-month"><</div>
<div class="month-item">July 2023</div>
<div class="arrows next-month">></div>
</div>
<div class="days=container"></div>
</div>
</div>
</div>
</div>
</div>
and this is my javascript, is there a way to do this shorter or better?
const date_picker_el = document.querySelector(".date-picker-container");
const days_el = document.querySelector(".dates-container");
function toggleDatePicker(e){
if(days_el.classList.contains("invisible")){
days_el.classList.remove("invisible");
days_el.classList.add("active:visible");
}else{
days_el.classList.remove("active:visible");
days_el.classList.add("invisible");
}
}
date_picker_el.addEventListener("click", toggleDatePicker);
Thank you for any help.
B.
Upvotes: 0
Views: 1078
Reputation: 89264
You can simply toggle the class.
days_el.classList.toggle('invisible');
Upvotes: 0