Adjust the height of a Vue.js div element

I am currently working with Vue.js and I need to adjust the height of one div based on the height of another div using pure JavaScript. The issue I am encountering is that I am unable to set the height using plain JavaScript, however it works fine with jQuery. Can someone help me convert this jQuery code to JavaScript? Below is the code snippet I am using:

Vue.nextTick(function () {
            var offsetHeight = document.getElementById('filterSection').offsetHeight;
            document.querySelector(".searchResultSection").style.maxHeight = `calc(100% - ${offsetHeight}px)`;
           });

I am looking to replace the jQuery part with vanilla JavaScript.

Answer №1

When it comes to solving your issue, computed properties (https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties) are the ideal solution:

Create a computed property that will determine the filterSectionHeight

export default {
  name: "App",

  computed: {
    filterSectionHeight() {
      const filterSectionDOM = document.getElementById("filterSection");
      return filterSectionDOM ? filterSectionDOM.offsetHeight : 0;   
    },
  }
};

Include the divs filterSection and searchResultsSection in your component (or App component), remember to add a :style attribute to handle the dynamic max-height for .searchResultsSection in your template

<div id="filterSection"></div>
<div class="searchResultsSection"
     :style="{
            'max-height': `calc(100% - ${filterSectionHeight}px)`
     }">
</div>

Ensure both divs have a height of 100% in your CSS

#app {
  height: 600px;
  width: 100%;
}

#filterSection {
  height: 100%;
  background: rebeccapurple; //https://en.wikipedia.org/wiki/Eric_A._Meyer
}

.searchResultsSection{
  height: 100%;
  background: rebeccapurple;
  opacity: 0.6;
}

You can see a complete demonstration here > https://codesandbox.io/s/1rkmwo1wq

Answer №2

Uncertain about the background of this modification, but I will provide some suggestions on how to accomplish it following best practices:

  1. If the parent element has a fixed height, then children with height: 100% will inherit the parent's height.

    .parent { height: 200px; }

    .child { height: 100%; }

  2. Consider using a vue-directive for manipulating the DOM: https://v2.vuejs.org/v2/guide/custom-directive.html

  3. Utilize v-bind:style="height: calc(100% - ${offsetHeight}px)\" on the specific element you intend to adjust the height of!

Answer №3

To achieve this, you should utilize the JavaScript DOM method. Give this a shot.

Vue.nextTick(function () {
   var offsetHeight = document.getElementById('filterSection').offsetHeight;
   var x = document.getElementsByClassName("searchResultSection");
   x[0].style.maxHeight = "calc(100% - ${offsetHeight}px)";
});

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

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

SWR failing to function effectively when used with asynchronous fetch operations

I recently updated SWR, and now I am facing issues with fetching my data properly. const { data: expressionsData, error: expressionsError } = useSWRImmutable( [`dashboard/expression/get-expression-analytics?startTime=${startDate}&endTime=${endDa ...

Send certain attributes from the main component to the subcomponent

When dealing with components, I often find myself needing to manipulate specific children based on their type. For example, in the code snippet below, I want to set additional props on a child component if it matches a certain type: import React from &apo ...

Using Vue to customize and edit a Google Maps marker

We are tasked with creating a collection of unique markers in Vue for a google map that can be easily updated as the map evolves. With over 100 markers expected on the map, which will remain visible for extended periods (3+ hours), we need to find a memo ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

What is preventing me from utilizing Jinja in JavaScript for a django website?

When using Python and Django framework for website development, one useful tool to incorporate is the jinja template engine. For instance: Rather than hard-coding an import like this: <script src="assets/js/onebutton.js"></script> We can do ...

Implementing siteSpeedSampleRate in Google Analytics with AngularJS - a step-by-step guide

I utilized the following link https://github.com/revolunet/angular-google-analytics to incorporate Google Analytics into my AngularJS 1.5 project. However, I'm having trouble setting the siteSpeedSampleRate. I injected the AnalyticsProvider and attemp ...

Utilizing multiple interactive dialog boxes with content pulled from JSON source

Welcome to the Mission Control Panel! On this interactive map, you can view mission markers and access detailed information for each mission by clicking on buttons inside the popups. Everything is dynamically generated from JSON data, so there are multiple ...

How can one choose the current element in jQuery.Treeview following a jQuery.load(html) event?

Within my HTML code in the sample.html file, I have the following structure: <ul id='topics' class='filetree'> <li><span class='folder'><a href='?Lang=en&TopicID=#'>Topics</a></s ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

Unexpected behavior with MongoDB update function

If I have a model like this: var stuffSchema = new mongoose.Schema({ "id": 1, "cars": { "suv": [], "sports": [], "supercar": [{ "owner": "nick", "previousOwners": [ ObjectId("574e1bc0abfb4a180404b17f"), ObjectId ...

Can you explain the distinction between "(.....);" and "{......}" within the context of React?

Encountering an error indicated in the image for the following code: handlechange(event) { this.setState (prevState => { return( checked : !prevState.checked );}); } Interestingly, changing the round brackets after "return" to curl ...

Set all form fields to ng-touched programmatically when the form is submitted

HTML: <div class="form-group" ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }"> <label for="firstName" class="control-label"> First Name </label> <input t ...

What could be causing the issue with my code where the canvas is not showing boxes beyond a y-coordinate of 8 along the x-axis?

I've been working on creating a 64 square checkerboard using the html canvas element in javascript, but I'm encountering an issue. The boxes aren't rendering properly after the first 8 squares on the y-axis, and I can't figure out where ...

Using a text box in jQuery to perform basic calculations is a straightforward process

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Creating a Lens Calculator Web App</title> <link href="http://code.jquery.com/mobile/1.0a3/jque ...

Preventing hyperlinks within a table from being recognized as the selected table row

I encountered a small issue while working on a webpage where clicking on a link within a table cell causes the entire row to be marked as clicked. However, I want only the link to trigger the click event, not the entire cell. You can view the jsfiddle he ...

JQuery was partially activated

Having just started using JQuery, I wanted to create a button that can dynamically change the colors defined in the CSS between blue and red when clicked, as well as updating the text displayed on the button. The draggable() function is working properly, ...

Every individual child component must be assigned a distinct key prop, even if they are pre-defined. - Utilizing REACT

My navigation bar routes are sourced from a JSON file structured like this: { "categorias": [ { "nombre": "Teacher absences", "componentes": [ { "type": "url", ...

Modify URL parameters in Vue.js based on specific conditions to remove key-value pairs

Currently, I am working on a filter feature where I need to append query parameters to the URL based on user selections. If a user chooses a specific option, I want to modify the query string accordingly. Here's an example of my current URL structure: ...

Tips for invoking a URL in an Ajax JSON request

Having trouble calling a webservice from a specific directory within my project. The URL I'm trying to access is "~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch" but it's not functioning as expected. $.ajax({ url: "~/RA/WebServiceRAOpe ...