The method window.matchMedia()
is used to execute a specified CSS media query and compare it with the current window state once. To ensure a responsive design, where code reacts to CSS media query changes as the window size changes, you can utilize the methods and event handlers provided by window.matchMedia()
.
For more information, visit www.w3schools.com/win_matchmedia.
To listen for state changes and add event listeners, follow these steps:
// Define the media query handler function
function myCSS_handler(x)
{
if (x.matches)
{
// Execute this code when the screen width is less than or equal to 767px
$(".services").css("display", "block");
$(".personal-detail").css("display", "none");
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
$(".personal-detail").css({ "opacity": "0.5", "color": "black" });
}
else
{
// Execute this code when the screen width is greater than 767px
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
$(".personal-detail").css({ "opacity": "0.5", "color": "black" });
$(".services").css({ "opacity": "1", "color": "#fff" });
}
}
// Wait for DOM ready
$(document).ready(function()
{
$(".billing-information").hide();
$(".services-information").css("display", "none");
// Call the listener function on button click
$("#next").click(function()
{
var x = window.matchMedia("(min-width: 767px)")
myCSS_handler(x) // Call listener function on button press
x.addListener(myCSS_handler) // Attach listener function on state changes
});
});
Alternatively, you can handle CSS based on screen width changes using the window resize function
, eliminating the need for media queries
. Here's an example approach:
// Function to dynamically adjust CSS based on screen width
function dynamic_CSS()
{
// Get the current window width
var width = $(window).width();
if(width <= 767) widthFrom_0_to_767();
else if(width > 767 && width <= 990) widthFrom_767_to_990();
else if(width > 990 && width <= 1300) widthFrom_990_to_1300();
else if(width > 1300 && width <= 1600) widthFrom_1300_to_1600();
else widthFrom_above_1600();
}
// Example function for screen widths up to 767px
function widthFrom_0_to_767()
{
$(".personal-detail").removeClass("give-color");
$(".services").addClass("give-color");
// Additional styling goes here
}
// Wait for DOM ready
$(document).ready(function()
{
$(".billing-information").hide();
$(".services-information").css("display", "none");
// Call the function on button click
$("#next").click(function()
{
dynamic_CSS(); // Execute the dynamic CSS adjustment function
});
// Adjust the CSS upon window resize
$(window).resize(function()
{
dynamic_CSS(); // Re-adjust the CSS on window resize
});
});