Coder Social home page Coder Social logo

mitera / vanilla-match-height Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 132 KB

A vanilla responsive equal heights

License: MIT License

CSS 11.82% HTML 55.96% TypeScript 32.22%
equal-height match-height vanilla same-height vanilla-javascript vanilla-js vanillajs

vanilla-match-height's Introduction

vanilla-match-height.js

License: MIT TypeScript Socket Badge jsdelivr npm npm downloads yarn

Inspired by: jquery-match-height

matchHeight: makes the height of all selected elements exactly equal

Demo - Features - Install - Usage - Options - Data API
Advanced Usage - Changelog - License

Demo

See the vanilla-match-height.js demo.

vanilla-match-height.js screenshot

Modern browsers

In the years since this library was originally developed there have been updates to CSS that can now achieve equal heights in many situations. If you only need to support modern browsers then consider using CSS Flexbox and CSS Grid instead.

Best practice

Use this library to match height of internal elements, like title or text of teasers

Features

  • match the heights for groups of elements automatically
  • use the maximum height or define a specific target element
  • anywhere on the page and anywhere in the DOM
  • responsive (updates on window resize)
  • row aware (handles floating elements and wrapping)
  • accounts for box-sizing and mixed padding, margin, border values
  • handles images and other media (updates after loading)
  • easily removed when needed
  • data attributes API
  • tested in Edge, Chrome, Firefox

Install

CDN via jsDelivr

<script src="https://cdn.jsdelivr.net/npm/vanilla-match-height@latest/dist/vanilla-match-height.min.js" type="text/javascript"></script>

Download vanilla-match-height.js and include the script in your HTML file:

<script src="vanilla-match-height.js" type="text/javascript"></script>

You can also install using the package managers NPM.

npm install vanilla-match-height

modular code

import 'vanilla-match-height'

Usage

document.body.matchHeight({elements: '.item'});

const containers = document.querySelectorAll(".items-container");
containers.forEach((container) => {			
    container.matchHeight({elements: '.item'});
});

Where options is an optional parameter.
See below for a description of the available options and defaults.

The above example will set all selected elements with the class item to the height of the tallest.
If the items are on multiple rows, the items of each row will be set to the tallest of that row (see byRow option).

Call this on the event (the plugin will automatically update on window load).
See the included test.html for many working examples.

Also see the Data API below for a simple, alternative inline usage.

Options

The default options are:

{
    elements: null,
    byRow: true,
    property: 'height',
    target: null,
    remove: null,
    attributeName: null,
    events: true,
    throttle: 80
}

Where:

  • elements is an optional string containing one or more selectors to match against. This string must be a valid CSS selector string
  • byRow is true or false to enable row detection
  • property is the CSS property name to set (e.g. 'height' or 'min-height')
  • target is an optional element to use instead of the element with maximum height
  • remove is an optional element/s to excluded
  • attributeName is an optional for use custom attribute
  • events is true or false to enable default events
  • throttle milliseconds to executed resize event, default is 80

Data API

Use the data attribute data-mh="group-name" or data-match-height="group-name" where group-name is an arbitrary string to identify which elements should be considered as a group.

<div data-mh="my-group">My text</div>
<div data-mh="my-group">Some other text</div>
<div data-mh="my-other-group">Even more text</div>
<div data-mh="my-other-group">The last bit of text</div>

All elements with the same group name will be set to the same height when the page is loaded, regardless of their position in the DOM, without any extra code required.

It's possible to use custom data attribute data-same-height="group-name"

<div data-same-height="my-group">My text</div>
<div data-same-height="my-group">Some other text</div>
<div data-same-height="my-other-group">Even more text</div>
<div data-same-height="my-other-group">The last bit of text</div>

const containers = document.querySelectorAll(".data-api-items");
containers.forEach((container) => {
    container.matchHeight({attributeName: 'data-same-height'});
});

Note that byRow will be enabled when using the data API, if you don't want this (or require other options) then use the alternative method above.

Advanced Usage

There are some additional functions and properties you should know about:

Manually trigger an update

window.dispatchEvent(new Event('resize'));

If you need to manually trigger an update of all currently set groups, for example if you've modified some content.

Row detection

You can toggle row detection by setting the byRow option, which defaults to true.
It's also possible to use the row detection function at any time:

Custom target element

const containers = document.querySelectorAll(".target-items");
containers.forEach((container) => {			
    container.matchHeight({elements: '.item-0, .item-2, .item-3', target: document.getElementById("target-item-1")});
});

Will set all selected elements to the height of the first item with class sidebar.

Custom property

const containers = document.querySelectorAll(".property-items");
containers.forEach((container) => {			
    container.matchHeight({elements: '.item', property: 'min-height'});
});

This will set the min-height property instead of the height property.

Where event a event object (DOMContentLoaded, resize, orientationchange).

Throttling resize updates

By default, the events is throttled to execute at a maximum rate of once every 80ms. Decreasing the throttle option will update your layout quicker, appearing smoother during resize, at the expense of performance. If you experience lagging or freezing during resize, you should increase the throttle option.

Manually apply match height

Manual apply, code for JavaScript framework/library (e.g. vue, react ...).

var el = document.body.matchHeight({elements: '.item'});
...
el._apply();
el._applyDataApi('data-match-height');
el._applyDataApi('data-mh');
el._applyAll();

Remove match height from elements

Reset inline style property

var el = document.body.matchHeight({elements: '.item'});
...
el._remove();

Remove events from match height elements

Remove events

var el = document.body.matchHeight({elements: '.item'});
...
el._unbind();

Known limitations

CSS transitions and animations are not supported

You should ensure that there are no transitions or other animations that will delay the height changes of the elements you are matching, including any transition: all rules. Otherwise the plugin will produce unexpected results, as animations can't be accounted for.

Vue3 Example:

import 'vanilla-match-height';
export default {
    name: 'Example',
    data: function () {
        return {
            matchHeight: document.body.matchHeight({elements: '.item p'})
        }
    },
    beforeUnmount() {
        this.matchHeight._unbind();
    },
    mounted() {
        this.matchHeight._apply();
    },
    methods: {
        reMatch() {
            this.matchHeight._apply();
        }
    }
}

React Example:

import 'vanilla-match-height';
class MyComponent extends Component {
    matchHeight = document.body.matchHeight({elements: '.item p'});
    componentDidMount() {
        this.matchHeight._apply();
    }
    componentWillUnmount() {
        this.matchHeight._unbind();
    }
    render() {
        return (
            ...
        );
    }
}

Not duplicate instance!

I suggest to assign element to a variable for not create multiple events instances

//Right solution
var el = document.body.matchHeight({elements: '.item'});
... json update
el._apply();

//Wrong solution
document.body.matchHeight({elements: '.item'});
... json update
document.body.matchHeight({elements: '.item'})._apply();

Changelog

To see what's new or changed in the latest version, see the changelog

License

vanilla-match-height.js is licensed under The MIT License (MIT)
Copyright (c) 2023 Simone Miterangelis

This license is also supplied with the release and source code.
As stated in the license, absolutely no warranty is provided.

vanilla-match-height's People

Contributors

mitera avatar miterangelis avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.