Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set height of a div in vue js

I am using vue js . I want to set one div based on another div height, with pure javascript. the problem I am facing is I can't set the height using pure java script. but I can set it using jquery. can any one please help me to change this jquery to javascript . the code I am using is given

 Vue.nextTick(function () {
            var offsetHeight = document.getElementById('filterSection').offsetHeight;
            $(".searchResultSection").css("max-height",`calc(100% - ${offsetHeight}px)`);
           });

I need to change the jquery part into java script.

like image 247
mr. Done Avatar asked Aug 05 '18 06:08

mr. Done


3 Answers

In fact, computed properties (https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties) is the perfect option to solves your problem:

Declare a computed property who will return the filterSectionHeight

export default {
  name: "App",

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

Define your div filterSection and searchResultsSection in your component (or App component), don't forget to add a :style attribute who handle the dynamic max-height provided to .searchResultsSection in your template

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

Set height of each div to 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 will find a full demo here > https://codesandbox.io/s/1rkmwo1wq

like image 52
Thomas Brd Avatar answered Nov 19 '22 08:11

Thomas Brd


Not sure about the context of this change, but I'll try to give you some solutions based on best practices on how to achieve that:

  1. If parent element has a fixed height, then children with height: 100% will adopt parents height.

    .parent { height: 200px; }

    .child { height: 100%; }

  2. Use a vue-directive for DOM manipulation: https://v2.vuejs.org/v2/guide/custom-directive.html

  3. Use v-bind:style="height: calc(100% - ${offsetHeight}px)\" on the element that you want to achieve the height!

like image 35
sadiqevani Avatar answered Nov 19 '22 09:11

sadiqevani


You need to use the javascript DOM-style to do this. Try this.

Vue.nextTick(function () {
   var offsetHeight = document.getElementById('filterSection').offsetHeight;
   var x = document.getElementsByClassName("searchResultSection");
   x[0].style.maxHeight = "calc(100% - ${offsetHeight}px)";
});
like image 1
Nuwan Alawatta Avatar answered Nov 19 '22 09:11

Nuwan Alawatta