Enquire.js does not compute accurately at first glance, but only after adjustments are made during

Currently, I am working on incorporating media queries using Enquire.js and Vue.js. The functionality seems to be in good shape when manually resizing the browser window. However, upon loading the document, no match is detected. This peculiar behavior becomes more apparent when toggling Chrome's device mode or accessing the site on a mobile device. Interestingly, everything works as expected when checking with the "Match & Unmatch Example" in said modes and devices. I am beginning to question if there is some sort of compatibility issue between Vue.js and Enquire.js, or could it be an error on my end?

The logic for the media queries resides within the ready hook of my Vue instance:

ready:
    function () {
        var self = this;
        enquire.register("screen and (max-width: 400px)", {
            match: function () {
                self.displayIsLarge = false;
                self.displayIsSmall = true;
            },
            unmatch: function () {
                self.displayIsLarge = true;
                self.displayIsSmall = false;
            }
        })
    );

Within my Vue instance, I have defined the following data properties:

var menu = new Vue({
el: '#app',
data: {
    displayIsLarge: true,
    displayIsSmall: false,

In my HTML file, I utilize v-if="displayIsSmall" and v-if="displayIsLarge" to show/hide elements based on the size of the browser window. Check out the JsdFiddle example here.

I started thinking that the issue might be resolved by utilizing the Setup callback, implementing some conditionals, like so:

enquire.register("screen and (max-width: 400px)", {
    setup: function() {
        if (this.match) {
            self.displayIsSmall = true;
        } else {
            self.displayIsSmall = false;
        }
    },
    match: function () {
        self.displayIsLarge = false;
        self.displayIsSmall = true;
    },
    unmatch: function () {
        self.displayIsLarge = true;
        self.displayIsSmall = false;
    }
})

However, this approach did not yield the expected results. Could you help identify what I am missing? Take a look at the JsdFiddle example here.


UPDATE

Even after trying Vue's beforeCompile and created hooks (replacing ready), I still haven't had any success.

Answer №1

If you transition from match to unmatch, the unmatch will only occur. This means it won't happen unless the screen width drops below 400px and then goes back over it. To approach this situation, I recommend taking a mobile-first approach and implementing something like the code below:

new Vue({
  el: '#app',
  data: {
    displayIsLarge: false,
    displayIsSmall: true
  },
  ready: function () {
    var self = this;
    enquire.register("screen and (min-width: 400px)", {
        match: function () {
            self.displayIsLarge = true;
            self.displayIsSmall = false;
        },
        unmatch: function () {
            self.displayIsLarge = false;
            self.displayIsSmall = true;
        }
    })
  }
})

Here's a small demo for reference: https://jsfiddle.net/crswll/uc7gaec0/

Although, depending on the content and functionality of these elements, it might be more efficient to toggle them using CSS for visual changes. You are more familiar with your project requirements, so you can decide which approach suits best.

Answer №2

To ensure that my webpage displayed correctly on both page load and after a resize, I followed the steps outlined in the previous answer. Additionally, I inserted a <meta> viewport tag into my index.html file. By including the following meta tag, the viewport scaled to fit the dimensions of the device, resulting in the proper styling for mobile devices:

<meta name="viewport" content="width=device-width, initial-scale=1">

The width=device-width setting establishes a correlation between the page width and the device's width, while initial-scale=1 determines the initial zoom level upon page load.

For more information, visit here.

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

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

Adapting language in real-time: DateTimePicker jQuery Plugin

I am looking to dynamically adjust the language settings of the DateTimePicker jQuery Plug-in (http://xdsoft.net/jqplugins/datetimepicker/) but I keep encountering an "undefined" error for the lang1 variable within the final plug-in function call: <!DO ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

What are effective solutions for addressing the CORS Policy issue in a Vue production build?

When developing my Vue.js app with Vue-CLI, I encountered an issue with CORS Policy errors after deploying the production version on nginx. The project uses a theme with Google fonts and MapBox, and everything works fine in the development server. The C ...

challenges with managing memory during express file uploads

I'm experiencing memory problems with file uploads while hosting my site on NodeJitsu. When I try to upload files, my app crashes with this error message: { [Error: spawn ENOMEM] code: 'ENOMEM', errno: 'ENOMEM', syscall: 'spa ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Django does not support running JavaScript natively

Wondering how to incorporate JavaScript into Django for creating chained forms? My first step was simply trying to understand how to run JavaScript. I've placed a basic main.js file in the static folder. I included a link to main.js in the header of ...

Include the <component> tag within a Vue.js template

Recently, I embarked on a journey to learn Vuejs and stumbled upon a single file component that has left me puzzled: <template> <component :is="user === undefined ? 'div' : 'card'"> ...some code </ ...

Leveraging Mongodb's aggregate feature to calculate the overall quantity of a specific product that has been ordered across all

Recently delving into the realm of javascript, I am currently tackling a dashboard project that requires displaying the total quantity of each product ordered. Although I have successfully defined a variable 'qty' to represent the quantity of an ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

What is the procedure to incorporate login credentials into the source of an iframe?

Is there a way to pass user auto login in the src URL? <iframe src="https://secure.aws.XXX.com/app/share/28228b0ccf0a987" width="1060px" height="1100px"></iframe> I attempted to achieve this, but it still shows the login screen <ifr ...

jQuery does not support iterating over JavaScript objects

Here is the code snippet I am working with: $(obj).each(function(i, prop) { tr.append('<td>'+ i +'</td>' + '<td>'+ prop +'</td>'); }); Intriguingly, the data in $(obj) appears as: Obje ...