window.matchMedia seems to only be effective when the window is refreshed

I've noticed that window.matchMedia works differently than using '@media only screen and' in CSS. With '@media', when the screen is narrowed, the changes happen automatically. However, with window.matchMedia, the screen needs to be loaded or refreshed, especially on desktop browsers. Is there a way to make window.matchMedia work more seamlessly like @media CSS, where the adjustments happen automatically as the screen-width is increased or decreased without the need for a manual refresh?

You can see an example of this being used on: Americastributetoparis.com

jQuery(document).ready(function($) {

if (window.matchMedia("(max-width: 800px)").matches) {
    // phone
    $(".front-page-1").backstretch(["/wp-content/themes/digital-pro/images/americas-tribute-to-paris-mobile.png"]);

} else {

    //tab or desktop
    $(".front-page-1").backstretch([BackStretchImg.src]);

}

});

Answer №1

I stumbled upon this piece of information while conducting research on a search engine, and decided to put it into action:

using media queries not only during runtime, but also when any changes occur to the window state
jQuery(document).ready(function($) {

var mql = window.matchMedia("(max-width: 800px)")

mediaqueryresponse(mql) // explicitly call listener function at run time

mql.addListener(mediaqueryresponse) // attach listener function to monitor state changes

function mediaqueryresponse(mql){
     if (mql.matches){ // check if media query matches

      // for phones
        $(".front-page-1").backstretch(["/wp-content/themes/digital-pro/images/americas-tribute-to-paris-mobile.png"]);

    } else {

      // for tablets or desktops
        $(".front-page-1").backstretch([BackStretchImg.src]);

     }
}

});

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

Attempting to replicate the flipping motion of a card by applying the transform property to rotate a div element, ultimately revealing a different

I am attempting to create a series of divs that simulate the flipping action of a notecard. Unfortunately, when I hover over the div, it turns white because I have set the display property to none. I am unsure how to make the other div (.back) visible. Y ...

I am looking to display the <AddProduct /> element within the main-content div of a different component called Dashboard

import { useState,useEffect } from 'react'; import './App.css'; import Header from './Components/Header/Header'; import { BrowserRouter as Router, Route ,Routes} from 'react-router-dom'; import Pages from './Pag ...

Is it possible for a Div's height to be equal to 100% of its container's

<div id="wrapper"> <div id="main-content"> //my main content </div> </div> #wrapper{ height:100%!important; min-height:700px!important; } #main-content{ height:100%!important; } Despite setting the height of my main ...

Is there a way to remove this annoying double Google search bar?

Looking to replicate the Google home page for a project using HTML and CSS. I'm having trouble with incorporating the highlighted code (as shown in the second picture and identified by bold and italicized text) into my code. When I try to add it, I en ...

Choosing a parent element with SASS/SCSS

I'm facing a slight issue with SCSS syntax while creating a small component using the BEM methodology. Here's the HTML: <div class="message message--success"> <div class="message__title"> BEM Example </di ...

How can I organize the form input fields into two columns?

I'm currently working on a project that involves using a form for project-based learning. However, I'm having trouble getting the form input to display in two columns. To achieve this, I've set up a main div called "container" with two neste ...

Determine the dimensions of child components within Svelte templates

I am currently in the process of transitioning a VanillaJS website to Svelte, and I need to have divs randomly positioned on the webpage. It's important to note that each div's size can vary depending on its content, so they cannot have a fixed s ...

Tips for identifying truncated text when resizing the td element

While using the resize option in my table, I noticed that it cuts off some text. How can I determine the size at which the text begins to get cut off? https://i.sstatic.net/X7tKK.png This issue occurs when I resize the header https://i.sstatic.net/peycT. ...

Header that sticks to the top of a container as you scroll through it

Many questions arise regarding sticky elements in the DOM and the various libraries available to handle them, such as jquery.pin, sticky-kit, and more. However, the issue with most of these libraries is that they only function when the entire body is scro ...

Utilizing Bootstrap design elements for a RadioButtonList

I am working on an ASP.NET WebForms application that includes a RadioButtonList which I want to style using Bootstrap's CSS classes. By utilizing the RepeatLayout="Flow" and RepeatDirection="Vertical" settings, the RadioButtonList will be generated i ...

Having four videos displayed on one webpage can cause the browser to function at a slower

I have videos that are around 30 seconds long and 15mbs. I'm wondering if it's feasible to include them on a page or if I should opt for cover images instead. I would like to use the video as a separator similar to the design showcased at Does a ...

Tips for resolving CSS div overlay issues

What is the solution to the div overlay issue? I have a div with two classes: col-sm-6. However, when I check the responsiveness, it overlaps the div. I'm unsure how to fix this. Can someone please assist me? I have attached an image of the output fo ...

Ways to apply a border-bottom to tr elements without affecting td elements

Is there a way to add a bottom border to <tr> elements without affecting <td> cells that have no border? I attempted the following approach, but setting border: 0 for <td> overrides the border for all <tr> elements as well, leaving ...

Storing crossed-out items in the browser's local storage for a task list

I am currently creating a to-do list and struggling with saving the CSS strike-through element into local storage. HTML CODE: <ul class="list-group"> <li *ngFor="let todo of todos; let i = index" class="list-group-item shadow p-3 mb- ...

Optimize Embedded Videos to Utilize Maximum HTML Element Width

I am facing an issue with embedding a Youtube video inside a td HTML element. I want the video to maintain its aspect ratio while expanding to fit the width of its parent td. My desired look for the video is like this: However, my current video appears l ...

Customize your menu in Wordpress to highlight active menu items with a unique style

I'm currently in the process of designing a WordPress template and focusing on customizing the menu. Here is what I have created so far: http://jsfiddle.net/skunheal/Umkyr/ However, there are two minor issues that I am struggling to address. In Word ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...

Hide the search bar's input field

I'm in the process of creating a responsive blog with a search input feature. However, I've encountered an issue where the search form input in my sidebar isn't collapsing properly and is overflowing outside of its designated container. Belo ...

Tap on the image placeholder to replace it with your own image

Just starting out, I have the following HTML code within a <form>: <div class="image-upload"> <img id="send_photo_img1" src="assets/images/index2.png"/> <input id="send_photo_input1" type="file"/> <img id="send_photo_img2" sr ...

What is the reason behind the lack of collapsing in an inline-block container that only contains floated items?

Within this design, there are 3 boxes arranged in a row using the float: left; property for each one. These boxes are contained within 2 other elements. Typically, these containers collapse due to the content being comprised of floated items. However, chan ...