Listen for changes in the clientWidth of an element in Vue 3

Hey there, I'm currently working on a project where I need to track the clientWidth of a component when it gets resized. I'm trying to achieve this by using:

const myEl = document.querySelector('#myID')

and monitoring changes in myEl.clientWidth. I haven't been able to find a function that specifically watches for element size changes, as most solutions focus on screen resizing. Here's an example of a function that works for screen resize:

import { onMounted, onUnmounted, ref } from "vue"
export default function () {
  let width = ref(window.innerWidth)
  const onWidthChange = () => width.value = window.innerWidth
  onMounted(() => window.addEventListener('resize', onWidthChange))
  onUnmounted(() => window.removeEventListener('resize', onWidthChange))
  return { width }
}

But what I'm attempting is slightly different:

import { onMounted, onUnmounted, ref } from "vue"
export default function (el) {
  let elWidth = ref(null)
  function onWidthChange(){
    console.log('HERE')
    elWidth.value = el.clientWidth
  }
  onMounted(() => el.addEventListener('resize', onWidthChange))
  onUnmounted(() => el.removeEventListener('resize', onWidthChange))
  return { elWidth }
}

I want to pass 'myEl' into the component and utilize it like so:

const myEl = ref(null)
onMounted(() => {
  myEl.value = document.querySelector("#myEl")
  const { elWidth } = useElementWidth(myEl.value)
  watch(() => elWidth.value,
    (wid) => {
       if(wid){
         console.log('widEL', wid )
       }
     },
  })
})

While being composable isn't mandatory, my main goal is to successfully monitor the clientWidth of the element.

Answer №1

Although I may not be an expert on resizeObserver, I have found that a component like this works well for my needs. It may not be perfect, but it serves its purpose for me. Feel free to make improvements as needed. I'm not certain if it works in every browser, but it seems to work fine in Chrome based on my testing.

import { onUnmounted, ref } from "vue"
export default function () {
  const elWidth = ref(0)
  const theEl = ref(null)
  const useElID = ref(null)
  function mountObserver(elID){
    useElID.value = elID
    console.log('elWidtMounted', elID)
    theEl.value = document.querySelector(elID)
    ro.observe(theEl.value);
  }
  onUnmounted(() => {
    console.log('elWidtUnMounted', useElID.value)
    ro.unobserve(theEl.value)
  })
  const ro = new ResizeObserver(entries => {
    console.log('Size changed', entries);
    for (let entry of entries) {
      console.log('Size changed e', entry);
      const width = entry.contentRect.width
      elWidth.value = width
    }
  });
  return { elWidth, mountObserver }
}

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

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...

Page resizing is disabled in Chrome after an Ajax load

I've been tirelessly working on the CSS for a website I'm building, and I've encountered a strange issue that only seems to affect Chrome. Firefox and Internet Explorer work perfectly fine. I am using jQuery to load HTML stubs and a signifi ...

Utilizing AngularJS and RequireJS to incorporate a controller into the view

I am facing an issue while trying to add an Angular controller to my HTML view. Typically, in Angular, this can be done using: ng-controller="<controller>". However, due to my use of RequireJS, I have had to implement it differently. I need to includ ...

Tips on how to modify database records rather than generating new ones

Currently, my team is developing a web application that utilizes wearables to monitor vital parameters. As part of our integration testing, we are using a Fitbit device. The app itself is built with Angular and JavaScript, while the database is hosted on C ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Steps to switch the primary audio input

Is there a way to change the default microphone of a client based on user selection? I can obtain the list of devices using the enumerateDevices promise, but how can 'Audio 40 USB' be set as the default microphone in this scenario? navigator.me ...

Difficulty displaying Vue components

Having inherited a troublesome codebase, I am facing an issue where the Vue components fail to load. The Vue framework seems to be mounting, but the components are not being displayed. This Laravel 5.7 application integrates blade templates with Vue elem ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

What is the reason for the undefined output of this verified JSON Web Token (JWT)?

I've been working on decoding a JWT id_token using the libraries jwks-rsa and jsonwebtoken, however, the result keeps coming back as undefined. I understand that this issue is related to callbacks and the need to wait for a response from the getKey f ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

Tips on placing custom loading components in Nuxt/Vue applications

I recently used nuxt and followed a helpful guide on creating a custom loading component. You can find the instructions here While the custom loader does work, I noticed that it appears in the same position as the original nuxt loader bar: https://i.stac ...

The 'openNewWin' property does not hold a valid Function object and is either null or undefined

I am currently working with an asp menu and trying to configure the navigateurl so that it opens in a new popup window. The issue I am facing is that when I execute the code, I encounter the following error: Error: The value of the property 'openNewW ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

What is the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

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" /& ...

Is it possible to utilize $regex alongside $all in mongoDB?

In my current project, I am facing a challenge where I need to handle an array of strings received from the frontend. Each document in my mongoDB database also has its own array of keywords. The tricky part is that the strings sent from the frontend migh ...

Confirmed the validation of an input that falls outside the parameters of the ReactiveForms model

Check out this StackBlitz example In my Angular application, I am utilizing a Reactive form with 3 inputs, each having its own validation. Additionally, there is an input that exists outside of the form within its own component, also with its own reactive ...