Skip to content

Instantly share code, notes, and snippets.

@AndreasHnida
Created March 20, 2024 08:20
Show Gist options
  • Save AndreasHnida/d2b79d18bb0cd2f4cc3325279f7e9764 to your computer and use it in GitHub Desktop.
Save AndreasHnida/d2b79d18bb0cd2f4cc3325279f7e9764 to your computer and use it in GitHub Desktop.
Displays a little square in the lower right corner with the current Uikit3 breakpoint the site is on. It reads the breakpoints from CSS, so changes in the builder will be reflected.
document.addEventListener('DOMContentLoaded', function() {
document.body.classList.add('cl1');
function watchBreakpoints() {
const body = document.body;
// Create badge element
const badge = document.createElement('div');
badge.id = 'breakpoint-badge';
badge.style.position = 'fixed';
badge.style.bottom = '0px';
badge.style.right = '0px';
badge.style.backgroundColor = 'black';
badge.style.color = 'white';
badge.style.padding = '5px';
badge.style.fontSize = '10px';
document.body.appendChild(badge);
function getBreakpoints() {
const breakpoints = {};
const rootStyles = getComputedStyle(document.documentElement);
// Read the custom properties for breakpoints
breakpoints.xs = parseInt(rootStyles.getPropertyValue('--uk-breakpoint-s'));
breakpoints.sm = parseInt(rootStyles.getPropertyValue('--uk-breakpoint-m'));
breakpoints.md = parseInt(rootStyles.getPropertyValue('--uk-breakpoint-l'));
breakpoints.lg = parseInt(rootStyles.getPropertyValue('--uk-breakpoint-xl'));
return breakpoints;
}
function checkBreakpoint() {
const width = window.innerWidth;
const breakpoints = getBreakpoints();
let activeBreakpoint = null;
for (const breakpoint in breakpoints) {
if (width >= breakpoints[breakpoint]) {
activeBreakpoint = breakpoint;
}
}
// Remove all breakpoint classes from the body
body.classList.remove('xs', 'sm', 'md', 'lg');
// Add the class corresponding to the active breakpoint
if (activeBreakpoint) {
body.classList.add(activeBreakpoint);
}
// Update the badge with the active breakpoint
badge.innerHTML = activeBreakpoint ? activeBreakpoint.toUpperCase() : 'NONE';
}
// Initial check
checkBreakpoint();
// Watch for resize events
window.addEventListener('resize', checkBreakpoint);
}
// Call the function to start watching for breakpoints
watchBreakpoints();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment