Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue:

<div id="banner-container" class="row">
    <div class="col-xs-12">
        <div class="card mb-2">
            <div class="banner banner-tag card-body" :style="getBannerStyle"></div>
        </div>
    </div>
</div>

Here is the relevant Javascript code and Vue computed property logic:

var container = document.getElementById('banner-container').offsetWidth;
...
computed: {
    getBannerStyle () {
        return 'width: ' + container + 'px;';
    }
}

Answer №1

getBannerStyle will not be reactive if it does not access any other reactive properties. To make it reactive, you should assign the offsetWidth value to a data property and reference that within getBannerStyle. You can achieve this by adding the following code:

mounted () {
  this.offsetWidth = document.getElementById('banner-container').offsetWidth
},
data () {
  return {
    offsetWidth: 0,
  }
},
computed: {
    getBannerStyle () {
        return `width: ${this.offsetWidth}px;`
    }
}

Answer №2

Regrettably, achieving this in pure Vue can be extremely challenging because the element might not have a size during any of the lifecycle hooks, particularly if it's not immediately visible on page load. Thankfully, all modern browsers come equipped with a handy class that can assist: ResizeObserver.

data: () => ({
    offsetWidth: 0,
    resizeObserver: null
}),
mounted() {
    this.resizeObserver = new ResizeObserver(this.onResize)
    this.resizeObserver.observe(document.getElementById('banner-container'))
    this.onResize()
},
beforeUnmount() {
    this.resizeObserver.unobserve(document.getElementById('banner-container'))
},
methods() {
    onResize() {
      this.offsetWidth = document.getElementById('banner-container').offsetWidth
    }
}

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

Is there a way for me to modify this carousel so that it only stops when a user hovers over one of the boxes?

I am currently working to modify some existing code to fit my website concept. One aspect I am struggling with is how to make the 'pause' function activate only when a user hovers over one of the li items, preventing the carousel from looping end ...

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

JavaScript text converter using split() method

I have a large amount of data in text format, similar to the following: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0b0d1b0c1b131f17124f3e19131f1712501d1113">[email protected]</a>:token1 | Time = US | Alphabe ...

By-passing Mistakes in Iteration in JavaScript

I have been working on using Google's Feed API to fetch images from a feed within an AngularJS controller. It successfully retrieves three images, but encounters an issue when it reaches a Twitter URL, causing the script to break. I would like it to s ...

Experience a glint in the React Suspense with React Router - Struggling with CSS properties post utilizing Suspense and Lazy

I'm experiencing an issue with my code where the CSS properties are not working properly when I wrap the code in suspense. The page loads and the suspense functions as expected, but the styling is not being applied. However, if I remove the suspense, ...

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Error rendering {message} object on the Chrome Console

In my ReactJS component, I am utilizing the {message} parameter from props. Check out the code snippet below: import React from "react"; const MyMessage = ({ message }) => { if (message?.attachments?.length > 0) { return ( < ...

Is there a way to minimize superfluous re-renders in React without resorting to the useMemo hook?

I am currently evaluating whether I should adjust my strategy for rendering components. My current approach heavily relies on using modals, which leads to unnecessary re-renders when toggling their visibility. Here is a general overview of how my componen ...

Receive axios responses in the exact order as the requests for efficient search functionality

Currently, I am working on integrating a search feature in React Native using axios. For the search functionality, I am incorporating debounce from lodash to control the number of requests being sent. However, there is a concern about receiving responses ...

Utilize HTML5, CSS, and Responsive Web Design to place four boxes into a div container

Is there a way to arrange four boxes inside a div so that they are positioned at the corners of the top-left, top-right, bottom-left, and bottom-right? And when you click on the box in the middle, a window opens with text. I'm looking for something s ...

User-triggered event not being emitted back from SocketIO server

In my React frontend, I am using socket.io-client and in the Express backend application, I am utilizing socket.io. There is an event on the server that sends a message to all users in a room when triggered. socket.on('connection', () => { ...

"Utilize Bootstrap's responsive 3-column grid layout for a sleek design, complete with hidden col-12 elements below each grid

Looking to create a 100% width column below an element within a column of a bootstrap grid. For better understanding, here is what I'm aiming for: https://i.stack.imgur.com/pl1Fi.png On selecting one of the images (from 1 to x), a hidden div with di ...

Leveraging jQuery to extract the value from a concealed form field

Seeking assistance with a jQuery issue... I am attempting to use jQuery to retrieve the values of hidden fields in a form. The problem I am facing is that there are multiple forms displayed on the same page (result set items for updating), and the jQuery ...

WordPress Migration Causing Issues with Custom Font Display

I recently moved my website from to using the Duplicator plugin, but I'm facing an issue with the custom font 'Kanit' not displaying correctly. I have double-checked on the backend and confirmed that Kanit font is properly set up. Below i ...

What is the best way to conceal the initial column using jquery?

Is there a way to automatically hide the first column of data as it loads from a csv file using jquery and AJAX? I know you can do this using onclick function, but I prefer to have it automatically hidden. How can I achieve this? Below is the sample CSV d ...

Identify alterations in an input field after selecting a value from a dropdown menu

Is there a way to detect changes in the input field when selecting a value from a drop-down menu, similar to the setup shown in the image below? html: <input type="text" class="AgeChangeInput" id="range"/> js:(not working) <script> $(docume ...