Resizable windows in html

jQuery on window resize

I have the following JQuery code:

The only problem is that this only works when the browser first loads, I want containerHeight to also be checked when they are resizing the window?

9 Answers 9

Here’s an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you’re just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

javascript

jQuery

How do I stop my resize code from executing so often!?

This is the first problem you’ll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It’s good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It «throttles» how often the code is called. This isn’t used as often with resize events, but it’s worth being aware of.

If you don’t have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

JavaScript window resize event

How can I hook into a browser window resize event?

There’s a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.

13 Answers 13

jQuery is just wrapping the standard resize DOM event, eg.

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I’m not sure if any of the browsers differ, but I’d encourage you to test in Firefox, Safari, and IE.

First off, I know the addEventListener method has been mentioned in the comments above, but I didn’t see any code. Since it’s the preferred approach, here it is:

Never override the window.onresize function.

Instead, create a function to add an Event Listener to the object or element. This checks and incase the listeners don’t work, then it overrides the object’s function as a last resort. This is the preferred method used in libraries such as jQuery.

object : the element or window object
type : resize, scroll (event type)
callback : the function reference

Then use is like this:

Читайте также:  Application permissions mac os

or with an anonymous function:

The resize event should never be used directly as it is fired continuously as we resize.

Use a debounce function to mitigate the excess calls.

window.addEventListener(‘resize’,debounce(handler, delay, immediate),false);

Here’s a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

This can be used like so.

It will never fire more than once every 200ms.

For mobile orientation changes use:

Here’s a small library I put together to take care of this neatly.

Solution for 2018+:

You should use ResizeObserver. It is a browser-native solution that has a much better performance than to use the resize event. In addition, it not only supports the event on the document but also on arbitrary elements .

Currently, Firefox, Chrome, Safari, and Edge support it. For other (and older) browsers you have to use a polyfill.

I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.

There are two main issues:

Never use object as a parameter name. It is a reservered word. With this being said, @Alex V’s provided function will not work in strict mode .

The addEvent function provided by @Alex V does not return the event object if the addEventListener method is used. Another parameter should be added to the addEvent function to allow for this.

NOTE: The new parameter to addEvent has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.

Here is the updated addEvent function with these changes:

An example call to the new addEvent function:

Resizable windows in html

Angular HTML Window

AngularJS module that provides a draggable and resizable window directive.
Based on https://github.com/rlamana/Ventus

This project is no longer maintained! However, feel free to fork and PR.

Install via npm

Install the package over npm.

Include in your project

Include the css and javascript in your html file.

And include it as a dependency in your application.

Creating a window

You can create windows by including the directive in your HTML. Use ng-repeat to iterate through a collection in the scope.

Specify options and handlers in the options object. These are the standard values:

Important: When using ng-repeat, you should provide a onClose handler function that deletes the window from your collection.

Events are broadcast on the scope where the window is attached. This means they are available to any controller inside of the ng-html-window container.

Dispatched when a window is resized, debounced to occur only every 50ms.

Only one window can have the focus. When a window gets focused (by clicking it), a broadcast with a reference to the window is sent to all child scopes:

The same goes for when a window looses the focus:

The extent of z-values used for the window layering ranges from and to those values.

Be sure to consider this when you want to display other elements on top or bellow the windows.

Читайте также:  How to make directory in windows

About

A resizable and draggable window directive for AngularJS

How to make HTML element resizable using pure Javascript?

I was wondering how we can make a HTML element like

tag element resizable when clicked using pure JavaScript, not the jQuery library or any other library.

10 Answers 10

I really recommend using some sort of library, but you asked for it, you get it:

Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE

what about a pure css3 solution?

See my cross browser compatible resizer.

Also see my example of resizer

I just created a CodePen that shows how this can be done pretty easily using ES6.

Basically, here is the class that does this.

just using the mousemove event in vanilla js

steps

add the mousemove to your target

listen to the target move event

get the pointer position, resize your target

codes

live demo

I have created a function that recieve an id of an html element and adds a border to it’s right side the function is general and just recieves an id so you can copy it as it is and it will work

There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a «div» as a reference element to drag it, and calculate the new dimensions or position of the original element.

Here’s an example that doesn’t use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!

See it in action with CodeSandbox:

In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:

/dev/energy

Сайт о том, как стать программистом и как с этим жить потом

Resizable элементы на странице и немного печенек

В этой заметке речь пойдёт о работе с JavaScript-фреймворком jquery-ui, а также с тем, что считают Вселенским Злом и чрезвычайно удобной вещью — технологией Cookies.
А именно, затронем вопрос динамического изменения размеров блоков и элементов мышкой.

Итак, для начала нам понадобятся сами файлы фреймворка.

Скачать их всегда можно с официального сайта.
Тут же подключаем полученные файлы к нашей страничке следующим кодом:

Это базовые стили наших элементов, а также фреймворки jQuery и jQuery-ui соответственно.

Теперь научимся подключать их к странице и настраивать.

Будем использовать следующую html-разметку

Обращаю внимание на то, что классы ui-widget-content и ui-widget-header идут «из коробки» в css плагина Resizable, соответственно, править их нужно там же.

Теперь активируем наш скрипт.

По идентификатору элемента мы присваиваем ему же масштабируемость (resizable). Базовая настройка плагина на этом завершается, а результат можно посмотреть в демо-примере номер 1.

Демо-пример 1

Теперь прикрутим к нашему ресайзбл-блоку немного плюшек для красоты. Встроенные свойства самого плагина Resizable помогут нам это сделать. Этих свойств достаточно много.

Читайте также:  Драйвер asus acpi для windows 10 что это

alsoResize – выбираем по селектору элементы, которые будут менять свои размеры вместе с текущим блоком.
animate – со значением true при изменении размера будет использоваться анимация.
animateDuration – может принимать значения ’slow’, ‘normal’, ‘fast’ или число в миллисекундах, определяющее длительность анимационного эффекта.
animateEasing – опция принимает строку с названием анимационного эффекта. Большое количество разнообразных эффектов можно использовать при условии подключения дополнительного плагина jQuery Easing. По умолчанию имеет значение ’swing’.
aspectRatio – при значении true по изменении размеров элемента будет сохраняться пропорция в соотношении сторон.
cancel –запрещает изменение размеров для элементов, указанных в этой опции.
containment – ограничивает изменение размеров внутри текущего элемента.
delay – число в миллисекундах, определяющее задержку старта ресайза элемента.
distance – количество пикселей, на которое переместиться указатель мыши, прежде, чем начнется изменение размеров элемента («защита от дурака» =) ).
ghost – при значении true по изменении размеров элемента будут видны его полупрозрачные контуры.
grid – в качестве значения принимает массив элементов [x, y], где x и y – числа, определяющие шаг сетки. Изменение размеров будет происходить дискретно, в соответствии с заданными значениями.
helper – принимает строку с названием css-класса, который добавляется к области, демонстрирующей во время перемещения размеры, в которые установится элемент.
maxHeight – максимальная высота.
maxWidth – максимальная ширина.

minHeight – минимальная высота.

minWidth – минимальная ширина.

Плюшки подключаются примерно так

А пример применения можно посмотреть ниже
Демо-пример 2

Всё это, конечно, хорошо. Но что делать, если один и тот же элемент повторяется в шаблоне страницы несколько раз? Ведь при переходе все его свойства будут возвращаться к исходным, и страница будет «скакать». И тут на помощь нам приходит технология Cookies. Да-да, от английского слова «печеньки». Это текстовый файл с параметрами, передаваемый браузеру, при заходе на страницу. О том, как пишутся данные в куки, сейчас я рассказывать не буду. А вот работу с ним я опишу.

Для того, чтобы писать в Cookies новые данные, нам потребуется ещё один плагин — jquery.cookie.js

Для того, чтобы записать параметры, используем следующий код

У jQuery ui события немного отличаются от событий простого JavaScript. Поэтому используем в коде конструкицю stop: function(event, ui). Она означает, что по остановке действия плагина ui-Resizable будут совершены какие-то действия. А именно, объявится переменная wdiv, в которую мы положим текущее значение ширины нашего div. Простыми командами этого тоже не сделаешь. Во фреймворке есть объект ui.size, который хранит текущие размеры изменяемого блока.
После этого значения записываются в cookie. Конструкция записи имеет следующий стандарт: $.cookie(«имя_куки», значение).

Всё, печенька готова. Однако, её необходимо прочитать и применить её данные к блоку. Это сделает вот такой код:

Суть такова: по событию готовности документа мы проверяем, есть ли куки с заданным именем (именем, которое мы задали в выставлении куки). Если они есть, то переменной orig мы присваиваем значение, которое там заложено. Затем применяем это значение к элементу с указанным селектором. В нашем случае это ширина блока.

На этом часть кода заканчивается, и можно наконец-то посмотреть третий демонстрационный пример!

Демо-пример 3

Спасибо за внимание, и безошибочного Вам кода!

Оцените статью