Trouble arising when implementing media queries alongside jQuery

When the screen size is 768px, I need to trigger the code below by clicking on the next button. However, an issue arises when trying to revert back to the original style after changing the screen size:

  $(document).ready(function() {
    alert();
    $(".billing-information").hide();
    $(".services-information").css("display", "none");
    $("#next").click(function() {
      alert();
      var mq = window.matchMedia("(max-width: 767px)");
      if (mq.matches) {
        $(".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" });
        $(".services").css({ "opacity": "1", "color": "#fff" });
      } else {
          $(".personal-detail").removeClass("give-color");
          $(".services").addClass("give-color");
          $(".personal-detail").css({ "opacity": "0.5", "color": "black" });
          $(".services").css({ "opacity": "1", "color": "#fff" });
      }
    });

Answer №1

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
     });
});

Answer №2

To incorporate your logic into a function, you have the flexibility to invoke it whenever the screen size changes or when the user clicks on the next button:

$( document ).ready( function () {
    alert();
    $( ".billing-information" ).hide();
    $( ".services-information" ).css( "display", "none" );
    $( "#next" ).click( next_button_function );
    $( window ).on( 'resize', next_button_function );


    var next_button_function = function () {
        alert();
        var mq = window.matchMedia( "(max-width: 767px)" );
        if ( mq.matches ) {
            $( ".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"
            } );
            $( ".services" ).css( {
                "opacity": "1",
                "color": "#fff"
            } );
        } else {
            $( ".personal-detail" ).removeClass( "give-color" );
            $( ".services" ).addClass( "give-color" );
            $( ".personal-detail" ).css( {
                "opacity": "0.5",
                "color": "black"
            } );
            $( ".services" ).css( {
                "opacity": "1",
                "color": "#fff"
            } );
        }

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to maintain scrollbars on mobile devices?

I'm currently building a cross-platform application using Angular 4 that needs to work seamlessly on both mobile and desktop devices. Is there a special trick to prevent the scrollbars from disappearing when viewing this page on a mobile browser? I&ap ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...

Center the table cell element horizontally

Struggling to align a table cell element both horizontally and vertically? Currently, only managing the vertical alignment. The images vary in size, calling for fluidity and compatibility with max-height and width... Custom Style Sheet (CSS) .prod-img { ...

How to create centered striped backgrounds in CSS

Attempting to achieve a background similar to the one shown Can this be accomplished using CSS? ...

What is the best way to retrieve the name/value pairs from a JSON object

function (data) { //add values based on activity type //data = JSON.parse(data); //alert(abc.Phone1); alert(data.myName) alert(data.toString()); if (activityType == "Phone") { } return; }, By observing the callback funct ...

Sending an Ajax request to C# code

UPDATE After some research, I discovered what seems to be the "correct way" to handle the issue by using a combination of JSON.stringify and creating a model, as explained in this thread. I still can't figure out why the original approach didn't ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Activate the function within the same class only for the selected item

Hello there, I'm struggling to grasp how to make this particular functionality work. Basically, I have 8 divs, each containing an image used as a button with the same class (tm-img), and hidden divs with additional information. My goal is to initiall ...

How can I personalize the preview feature in a Bootstrap rich text editor?

Currently, I am utilizing Bootstrap's rich text editor by this method $('#editor').wysiwyg();. Utilizing AJAX, I am passing the HTML content created by .wysiwyg to save it in the database. Later on, I plan to retrieve the saved HTML data to ...

When I submit a form with an empty date input field, the Datepicker is sending a 0000-00-00 date

[I am experiencing an issue with my date input field. When I submit without entering any value, the date on the view page shows as 0000-00-00 instead of being empty or blank.] <div class="col-sm-3 col-sm-offset-1"> <div class="input-group"& ...

What is the best technique to position a div at the bottom of a container that has a height of 100

After many attempts and searching for answers, I'm still struggling to figure out how to make the div float to the bottom with 100% height. I've even considered if it's an issue with Pure or something else entirely. It's definitely frus ...

There is a lack of CSS import in the HTML document

I have organized my files in the following structure: - index.html - css/styles.css This is the HTML code I am using: <!DOCTYPE html> <html lang="en> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> & ...

Display search results within the same page using jQuery, without redirecting to a new page

I am currently working on creating a custom search form for an e-commerce platform using Magento. This search form consists of multiple dropdown select boxes. While the form is operating correctly, once the form is submitted with selected search criteria, ...

Fetching form data using the .add method in PHP

I'm facing an issue where I upload a text/plain file and use jQuery AJAX to pass it to PHP for processing. However, the jQuery AJAX call is returning an error: jquery-2.2.3.js:8998 Uncaught TypeError: Illegal invocation https://i.sstatic.net/eFjYF.png ...

Tips for styling a PHP file using CSS and styling more than one element:1. Begin by creating a

I am currently attempting to style a php file using a linked stylesheet, but I am encountering some difficulties. At the moment, I have the , it will affect either the font or the border.</p> Is there a way to apply multiple styles to elements on a ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

Can you explain the distinction between max-width and min-width in media queries for HTML and CSS?

Could you explain the distinction between max-width and min-width in media queries in HTML and CSS? @media (min-width:480px) { /* styles for smartphones, Android phones, and landscape iPhone */ } @media (min-width:600px) { /* styles for portrait tabl ...

What is more effective: generating/eradicating HTML components or concealing them until required?

When it comes to showing/hiding content, there are two main approaches that I would consider: Creating and destroying elements as needed using jQuery's append() and remove() methods. Having all elements already in the HTML but hiding/disabling them ...

css center arrow-aligned underline text

Trying to emphasize my text with an additional arrow centered on the line is proving to be a challenge. When attempting this, the text does not align in the center of the page. .souligne { line-height: 17px; padding-bottom: 15px; text-transform: u ...

Arrange flex list items in vertical rows on smaller screens for a more organized layout

Struggling to have CSS flex list stagger text on two lines for smaller screens, but so far, my attempts have failed. I've tried using spans and br at various media queries, but nothing seems to work. Any assistance would be greatly appreciated. This ...