jQuery to manage the height of dynamically generated content

Using jQuery and CSS to make a list scroll-able based on the height of a dynamically generated list of content in HTML to prevent style demolition.

Here’s a simple javascript function to help manage huge list that are automatically generated. The simple script will first calculate the height of the element through the DOM and them if the height exceeds the lime then adds a css to the element making it scroll-able so as not to break any elements on the site.manageHeight jQuery

The problem is that when you use some CMS that you cannot control the backend code. Something like Shopify, Weebly and the likes where the you’re limited in what you can do in the back-end but can add HTML, CSS, and JavaScript to the pages. If you have a big list of categories dynamically generated you can get a single category in a page or a hundred. This little hack makes it easy to control it without having to make a single off CSS style for every page.

-JavaScript Code-


function manageHeight(elm, height){
var h = $(elm).height();
if (h>height){
$(elm).css("height", height)
}
}
manageHeight('.brandslist', 200);

-CSS Code-

.brandslist{
overflow: auto;
}

The function manageHeight takes two attributes: the elm which is a jQuery selector. The height attribute is to check for the height of the element and if the element is higher than the value, an inline CSS attribute is added to the element.

The CSS code allows the list to be scroll-able so that it doesn’t the style of the website and disrupt the use experience.

Once these are set up, once the code loads into the page, it will check the height of the element, if the element is higher than the height value of the function. The height css attribute is added which makes the element scroll-able.

For example, when a list of 3

  • elements load inside, it may not take more than 200px height. In this case the code wouldn’t do anything an the element will fit into it’s parent element. But when more elments (say 50
  • elements) load, the height of the element would grow more than 200px, this is where the code will execute to add the inline CSS and make it scroll-able instead.
non scroll-able and scroll-able list
non scroll-able and scroll-able list with jQuery

 

Here’s a demo of the code running in codepen:
https://codepen.io/nirose/pen/bpRQjb

I’m not a perfect developer so I’m open for advice or simpler way to do this. Would appreciate any comment on how bad it is.

Leave a Reply