ru
en

Npm package: hq-modal

hq-modal is an exceptionally simple utility for managing and configuring modal windows on a web page, helping you quickly set up and launch modals.
Modal
Popup
Dialog window
Windows

Npm Package Description

en Hq-Modal is an exceptionally simple utility for managing and configuring modal windows on a web page. It helps you quickly set up and trigger modals.

The library allows you to:

  • Set the modal window width
  • Control its position on the page
  • Customize the overlay color
  • Show or hide the close button
  • Fix content shift when opening a modal
  • Close modals on Escape key or outside click
  • Block scrolling and interaction with the background
  • Responsive: works well on mobile without blocking content
  • Lightweight (~2KB minified), with zero dependencies

Installation

Several usage and installation options:

Option 1 – NPM

Install via npm:

npm install hq-modal --save-dev

Option 2 – Use from CDN

<script src="https://unpkg.com/hq-modal@latest/dist/hq-modal.umd.js"></script>

Setup

1 – Define the modal window

In HTML, define the modal block using data-hq-modal-block="test-name" and hidden.

Replace "test-name" with any name you like.

Example:

<div data-hq-modal-block="test-name" hidden>
  <!-- modal content -->
</div>

2 – Add modal trigger elements

To trigger the modal, assign the attribute data-hq-modal-button="test-name" to any element.

"test-name" should match the name used in the previous step.

Example:

<button data-hq-modal-button="test-name">Open Modal</button>

Optional close buttons inside modal

If you'd like to add extra close buttons inside the modal, assign the attribute data-hq-modal-close to them.

Note: This is for internal buttons only. The built-in close button is controlled by the showButtonClose option during initialization.

Example:

<button data-hq-modal-close>Close</button>

Usage

Initialization and basic configuration:

If using NPM, import the module:

import HqModal from 'hq-modal';

If using CDN, just initialize:

Initialization

const testName = new HqModal('test-name');

With configuration options

You can also pass in configuration options:

const testName = new HqModal('test-name', {
  maxWidth: '400px',
  background: 'rgba(0, 0, 0, 0.5)',
  top: '10px',
  left: '100px',
  showButtonClose: true,
});

Options reference

Option Type Default value Description
maxWidth string '500px' Sets the modal window width.
background string 'rgba(0, 0, 0, 0.4)' Overlay background color (supports HEX, RGB, RGBA).
top string '0px' Top offset. (use either top or bottom)
bottom string '0px' Bottom offset. (use either top or bottom)
left string '0px' Left offset. (use either left or right)
right string '0px' Right offset. (use either left or right)
showButtonClose boolean false Whether to show a built-in close button.

⚠️ Note: top and bottom should not be used together — choose one. Same applies to left and right.


Requirements and Compatibility

  • Can be used as an ES module
  • Can also be used as a UMD bundle (hq-modal.umd.js is included or via CDN)
  • Works in all modern browsers

License

This project is licensed under the MIT License.

Hq-Modal — это исключительно простой утилитарный инструмент для управления и настройки модальных окон на веб-странице. Он помогает быстро настроить и вызвать модальные окна.

Библиотека позволяет:

  • Задать ширину модального окна
  • Контролировать его позицию на странице
  • Настроить цвет оверлея
  • Показать или скрыть кнопку закрытия
  • Исправить сдвиг контента при открытии модального окна
  • Закрывать модальные окна по нажатию клавиши Escape или клику вне окна
  • Блокировать прокрутку и взаимодействие с фоном
  • Адаптивность: отлично работает на мобильных устройствах без блокировки контента
  • Легковесность (~2KB в минифицированном виде), без зависимостей

Установка

Несколько вариантов использования и установки:

Вариант 1 – NPM

Установка через npm:

npm install hq-modal --save-dev

Вариант 2 – Использование через CDN

<script src="https://unpkg.com/hq-modal@latest/dist/hq-modal.umd.js"></script>

Настройка

1 – Определите модальное окно

В HTML определите блок модального окна, используя атрибут data-hq-modal-block="test-name" и атрибут hidden.

Замените "test-name" на любое имя по вашему выбору.

Пример:

<div data-hq-modal-block="test-name" hidden>
  <!-- содержимое модального окна -->
</div>

2 – Добавьте элементы для вызова модального окна

Для вызова модального окна присвойте атрибут data-hq-modal-button="test-name" любому элементу.

"test-name" должно совпадать с именем, использованным на предыдущем шаге.

Пример:

<button data-hq-modal-button="test-name">Открыть модальное окно</button>

Необязательные кнопки закрытия внутри модального окна

Если вы хотите добавить дополнительные кнопки закрытия внутри модального окна, присвойте им атрибут data-hq-modal-close.

Внимание: это для внутренних кнопок. Встроенная кнопка закрытия контролируется опцией showButtonClose при инициализации.

Пример:

<button data-hq-modal-close>Закрыть</button>

Использование

Инициализация и базовая настройка:

Если используете NPM, импортируйте модуль:

import HqModal from 'hq-modal';

Если используете CDN, просто инициализируйте:

Инициализация

const testName = new HqModal('test-name');

С параметрами конфигурации

Также можно передать параметры конфигурации:

const testName = new HqModal('test-name', {
  maxWidth: '400px',
  background: 'rgba(0, 0, 0, 0.5)',
  top: '10px',
  left: '100px',
  showButtonClose: true,
});

Справочник опций

Опция Тип Значение по умолчанию Описание
maxWidth string '500px' Задает ширину модального окна.
background string 'rgba(0, 0, 0, 0.4)' Цвет фона оверлея (поддерживает HEX, RGB, RGBA).
top string '0px' Отступ сверху. (используйте либо top, либо bottom)
bottom string '0px' Отступ снизу. (используйте либо top, либо bottom)
left string '0px' Отступ слева. (используйте либо left, либо right)
right string '0px' Отступ справа. (используйте либо left, либо right)
showButtonClose boolean false Показывать ли встроенную кнопку закрытия.

⚠️ Важно: top и bottom не должны использоваться одновременно — выберите один. То же касается left и right.


Требования и совместимость

  • Может использоваться как ES-модуль
  • Может также использоваться как UMD-бандл (hq-modal.umd.js включён или доступен через CDN)
  • Работает во всех современных браузерах

Лицензия

Этот проект лицензирован под MIT License.

Contact us
Send a request for the project of your web service or application and we will contact you
By clicking on the button, I agree to the processing personal data

We are trusted by customers from more than 30 countries

USARussiaEU
Up