How to useJavaScript and Media Queries in Javascript
In this apporcah, we are using the JS and Media Queries to dynamically track the active Tailwind CSS breakpoint. JS checks dor the widow’s width against the predefined breakpoints using media queries.
Syntax:
function getActiveBreakpoint() {
if (window.matchMedia('(min-width: 1280px)').matches) {
return 'xl';
} else if (window.matchMedia('(min-width: 1024px)').matches) {
return 'lg';
} else if (window.matchMedia('(min-width: 768px)').matches) {
return 'md';
} else if (window.matchMedia('(min-width: 640px)').matches) {
return 'sm';
} else {
return 'default';
}
};
Example: In this example, we have used ‘window.matchMedia’ to check the current window width against the predefined breakpoints.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Tailwind Active Breakpoint</ title > < link href = "https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel = "stylesheet" > </ head > < body class = "bg-gray-100" > < div class="flex justify-center items-center h-screen"> < div class="bg-green-800 text-white p-6 rounded-lg shadow-lg"> < h1 class="text-2xl font-semibold mb-4"> Active Tailwind Breakpoint: </ h1 > < div id = "break-info" class = "text-3xl font-bold" > </ div > </ div > </ div > < script > function getActiveBreakpoint() { if (window.matchMedia( '(min-width: 1280px)').matches) { return 'xl'; } else if (window.matchMedia( '(min-width: 1024px)').matches) { return 'lg'; } else if (window.matchMedia( '(min-width: 768px)').matches) { return 'md'; } else if (window.matchMedia( '(min-width: 640px)').matches) { return 'sm'; } else { return 'default'; } } function updatingBreakInfo() { const breakInfo = document.getElementById('break-info'); const activeBreakpoint = getActiveBreakpoint(); if (activeBreakpoint) { breakInfo.textContent = activeBreakpoint; } } window.addEventListener('resize', updatingBreakInfo); updatingBreakInfo(); </ script > </ body > </ html > |
Output:
How to Get Tailwind CSS Active Breakpoint in JavaScript ?
In JavaScript, a Tailwind CSS active breakpoint refers to a specific breakpoint configuration in the Tailwind CSS framework that is currently active, which allows web designers to target specific screen sizes and also consider their styles and functionalities efficiently. In this article, we will see how we can get Tailwinds active breakpoints in JavaScript.
There are two common methods that can be used to get tailwinds active breakpoint in JavaScript, which are listed below:
Table of Content
- Using Tailwind CSS Utility Classes
- Using Javascript and Media Queries
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us