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

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

The Laravel function is not returning as expected on the server

I'm facing an issue with my Laravel project. When the validator fails, the return back function works fine on localhost but on the server it redirects to the root URL. Can anyone help me resolve this problem? Here is my controller code: public functi ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

Search through an array of objects that contains nested arrays of objects with various property names and values

I have an Array of objects structured like this: [{ property1: 'test', property2: 'test', filter: [{ fil1: 1, fil2: 2, fil3: 3 }, { fil1: 56, fil2: 3, fil3: 34 ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...

I have successfully implemented an onChange function with its corresponding set of parameters. However, I now desire to extend its functionality by incorporating

I have an onchange function that triggers when the "pending" option is selected in a select dropdown menu. This function adds a predefined value to an input field. However, I also want this functionality to apply when the page loads. Currently, the "pendin ...

Content must be concealed following the third paragraph

Dealing with an API that generates content in p tags, which can become excessively long. Considered hiding the content after 400 characters, but it poses a risk of cutting through HTML tags. Instead, looking to hide the excess content after 3 paragraphs a ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...

Leveraging NodeJS to handle server-side tasks and operations

Background: I am exploring the use of NodeJS for a project that involves scraping and storing content in Mongo. This process needs to be automated according to a set schedule. In addition, I need functions that can extract items from the Mongo database, o ...

"Problems with the YouTube API functions: playVideo, pauseVideo, and stopVideo not

Currently, I am working on integrating the YouTube API to control a group of players within a slideshow. My goal is to pause and play videos based on which slide the slideshow is on. I have tried storing the players in an array using the frame's id. W ...

"Utilize Ajax to trigger a custom alert message once data is loaded and ready

Is it possible to customize the data object in order to show a JavaScript alert saying "The email address has already been registered!"? Currently, the servlet returns a boolean indicating whether the email is already in the database. $('#emailInput ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

Are there any cross-platform inter-process communication APIs available in both C++ and Javascript?

In the process of developing an app, I am faced with the challenge of passing messages between a C++ application and a Javascript web app. While I have experience writing sockets code in both languages when required, I am now looking for a higher-level me ...

The function Array.map is unavailable, causing the datalist to not update as expected

I've been closely following a tutorial series on YouTube, but I keep encountering an error during the process. The link to the tutorial is available here: https://www.youtube.com/watch?v=re3OIOr9dJI&t=11s&ab_channel=PedroTech. The purpose of ...

Securing Your Frontend Routes in Vue.js and Laravel: Best Practices

How can I secure my Vue.js Route for the frontend? I am building a blog application using Laravel and Vue.js, but I'm facing an issue where if the admin is logged in and tries to access the frontend URL, it redirects to the login panel. How can I prev ...

VueJS not updating data variable as expected upon click event triggering function

This particular block of code is designed to control the visibility of Facebook-like dropdown mini-tabs by toggling data. The issue here is that every toggling function is triggered upon a click event, but some functions update data variables while other ...

Is there a proven method to instantly update local state in React/Redux without needing to wait for a response from an API call?

Summary: Are there any well-known solutions using React/Redux to achieve a fast and responsive UI, while seamlessly updating an API/database even in cases of failed requests? I want to develop an application featuring a "card view" functionality using htt ...

What is the most effective way to retrieve the default value of ng model?

When working with php and angular, I am trying to set a value in ng model from a php expression. However, when I try to read the ng model value from the controller, it is showing up as null. <input ng-model="id" ng-init="id= '<?php echo $userID ...

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...