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

Issues with data communication in AJAX and Node JS/Express post requests

I'm currently exploring Node.js and I'm running into an issue with app.post. Everything seems to be working fine, as I can see the console log whenever the action is executed. However, the data sent by AJAX from main.js does not seem to be receiv ...

Guide to modifying WordPress version 4.5 with HTML pages

I am encountering issues with my Wordpress website. I have installed it on Softcald in cPanel and now I want to edit my Wordpress using HTML. However, I am having trouble finding the editing option. My Wordpress version is 4.5 and I have searched online ...

Filter Form Inputs using JQuery by Class and Value

I am currently utilizing AJAX to submit form values and I require the ability to extract values based on class rather than id. The form from which I am gathering information will be utilized multiple times within the web application. With a blend of Framew ...

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

Ways to enlarge the diameter of the inner circle

I've implemented some CSS with JQuery, as seen in this JSFiddle. However, I'm having trouble increasing the width and height of the green circle to be slightly larger than the gray circle (referred to as the main circle) which is positioned at a ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

Fade in and fade out elements with jQuery using opacity in Internet Explorer

I have encountered an unusual issue in Internet Explorer involving a CSS Overlay used for a lightbox. The problem arises when I apply the fadein and fadeout effects using jQuery - everything seems to work smoothly except in IE. Instead of displaying a smo ...

What are the steps to make a dropdown menu using only HTML and CSS?

Can someone please share the most straightforward method for creating a drop-down list using just HTML and CSS? ...

Having trouble retrieving information from the database with jquery

I am facing an issue with retrieving data from a database on click and inserting that data into a Bootstrap modal for editing. The functionality works well when I have a string in the database, but it fails to load when there is an array or when the field ...

Why is it that the LESS compiler fails to recognize classes that are created by a zero iterator

When working with my CSS sheet, I found that I needed to reset some Bootstrap 3 preset values in order to achieve my desired style. To do this, I started using utility classes like .m-b-0 which sets margin-bottom:0px. However, I encountered an issue with ...

Is there a method to consistently keep the horizontal scrollbar in view for the MUI Data Grid at all times?

I have a Data table with virtualized columns, totaling more than 25 in number. Users can easily scroll horizontally using a trackpad, but without one, they may struggle to access all the columns due to the delayed appearance of the scrollbar. Is there a w ...

What is the best way to obtain real-time DOM updates using jQuery?

Upon loading my webpage, various scripts are adding a significant amount of HTML code. Now, I am attempting to modify this additional HTML. For instance, there is a div element <div id="detail"><span>some content</span></div> that ...

Using AngularJS for dynamically generated HTML elements that have not been loaded into the DOM involves creating an AngularJS directive that manages

Hey there! I'm a newcomer to AngularJs and I'm currently fetching HTML data from C# through an ajax call. I'm attempting to incorporate AngularJs functionality for the dynamically generated HTML, but unfortunately I'm not seeing any Ang ...

Retrieve the child DIV element within its sibling without using an identifier

I have a setup similar to the following: <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Tiger128 (v2)</h3> </div> <div class="panel-body"> <inp ...

Could the ajax call possibly complete after the execution of the next line of code?

$("#ajaxform").submit(function(e){ var info = $(this).serialize(); $.ajax( { url : "controller", type: "post", data : info, success:function(data, textStatus, jqXHR) { ...

Having trouble incorporating custom CSS into my Rails/Bootstrap project

I’m having trouble figuring out what I’m doing wrong. I’ve added custom files and tried to override the existing ones. application.css.scss @import 'bootstrap-sprockets'; @import 'bootstrap'; /* * This manifest file will be co ...

Unknown CSS element discovered: bootstrap, gradient, carousel

I recently created a random quote app using javascript, jQuery, and bootstrap on Codepen. Everything worked perfectly there. However, when I organized the files, pushed them to git, and tried to view the app from Safari, I encountered some warnings and t ...

Obtain an image from CSS using :after with jQuery

In my attempt to create a button animation where checkboxes in the .focus state should display their assigned background: url("x.svg"); from the CSS file, I have encountered an issue with my markup. I am struggling to make the :after element appear on the ...

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...