- jQuery метод .resize()
- Определение и применение
- jQuery синтаксис:
- Добавлен в версии jQuery
- Значения параметров
- Пример использования
- Отслеживаем «onresize» на элементе
- Тест-Код:
- Читают сейчас
- Редакторский дайджест
- Похожие публикации
- Типобезопасность в JavaScript: Flow и TypeScript
- Работа с датой и часовыми поясами в JavaScript
- Сочиняя ПО: Почему стоит изучать ФП на JavaScript?
- Заказы
- Минуточку внимания
- Комментарии 23
- JavaScript window resize event
- 13 Answers 13
- JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
- 12 Answers 12
- Cross-browser window resize event — JavaScript / jQuery
- 11 Answers 11
jQuery метод .resize()
Определение и применение
jQuery метод .resize() привязывает JavaScript обработчик событий «resize» (срабатывает при изменении размеров окна браузера), или запускает это событие на выбранный элемент.
Обратите внимание на то, что в зависимости от браузера пользователя, количество срабатываний события «resize» может отличаться, некоторые браузеры отправляют событие постоянно, когда изменение размера окна браузера происходит (типичное поведение в Internet Explorer и браузеров на основе WebKit, таких как Safari и Chrome), или только один раз в конце операции изменения размера окна (типичное поведение в некоторых других браузерах, таких как Opera). По этой причине код используемый в обработчике этого события не должен быть зависим от количества срабатываемых раз.
jQuery синтаксис:
Обращаю Ваше внимание, что метод .resize(), используемый вместе с функцией, переданной в качестве параметра (handler) является, короткой записью метода .on(), а без параметра является короткой записью метода .trigger():
Добавлен в версии jQuery
Значения параметров
Параметр | Описание |
---|---|
eventData | Объект, содержащий данные, которые будут переданы в обработчик событий. |
handler | Функция, которая будет выполнена каждый раз, когда событие срабатывает. Функция в качестве параметра может принимать объект Event . |
Пример использования
В этом примере с использованием jQuery метода .resize() мы при нажатии на элемент (кнопка) вызываем событие «resize» на объектe window , которому задали, что при срабатывании события «resize» необходимо получить значение ширины области просмотра браузера и вставить его в элемент
Результат нашего примера:
Пример использования jQuery метода .resize() (без параметров и с функцией) jQuery события
Отслеживаем «onresize» на элементе
Достаточно древняя задача отслеживания события изменения размеров произвольного элемента на странице. Актуально при создании модульно-независимой структуры для корректировки размеров и иных сss-атрибутов нужного элемента на странице, в частности блоков с периодической Аякс-подгрузкой (например: новостных). Типично решается через таймирование и периодический опрос размеров элемента. Новый вариант, — не использующий таймирующий опрос.
Трюк: Внутрь элемента вставляем пустой фрейм с position:absolute и 100%- (ыми) размерами, придаём элементу position:relative; . И отслеживаем frame.onresize :
Тест-Код:
Под спойлером
Читают сейчас
Редакторский дайджест
Присылаем лучшие статьи раз в месяц
Скоро на этот адрес придет письмо. Подтвердите подписку, если всё в силе.
Похожие публикации
Типобезопасность в JavaScript: Flow и TypeScript
Работа с датой и часовыми поясами в JavaScript
Сочиняя ПО: Почему стоит изучать ФП на JavaScript?
Заказы
AdBlock похитил этот баннер, но баннеры не зубы — отрастут
Минуточку внимания
Комментарии 23
скажите, пожалуйста, а чем этот метод хорош? я, правда не копал глубоко, но мои знакомые, когда делали для своего проекта фреймворк, руководствовались следующим образом: событие onresize может не всегда вызываться, а может вызываться сотню раз даже тогда, когда ничего не меняется. И еще, это поведение нужно учитывать во всех браузерах.
Так вот, если вызывается метод, который может изменить состояние DOMa, они сравнивали значения новых размеров со старыми. Если было различие, то собственное событие onresize вызывалось, иначе — нет.
я описал этот подход очеь грубо, так как в дебри не лез. Но, в принципе, это позволяло снять нагрузку с обработчика события (например, просчет размеров родителей или детей, если используется свой механизм ресайзинга).
просто мне кажется, что добавление айфрейма без источника в каждый нужный элеменет, это как-то накладно.
Vest сказал(а): просто мне кажется, что добавление айфрейма без источника в каждый нужный элеменет, это как-то накладно.
Во первых: вряд ли есть необходимость cтавить на каждый элемент, правильнее тогда уж на весь window однократно. Во вторых — типичное решение: это таймирование в реальном масштабе, это интервал опроса размеров не более 200ms. Однократная установка iframe или же бесконечный опрос по таймеру? (считаем пока для единичного экземпляра)
По таймеру накапливается и какой то мусор в процессе таймирования и, если смотреть загрузку процессора, — таймирование её существенно повышает.
Собственно пустой фрейм достаточно неплохое решение для контроля размеров на нескольких элементах.
Зы: Пустой фрейм даже не требует типичной загрузки и ставиться в DOM сразу.
я не говорил про таймер. в том-то и дело, вы если контроллируете страницу можете узнать когда вам необходимо проверить кусок ДОМа на ресайз. Предположим, вы загрузили контент динамически, проверили размер элемента и выстрелили бы событие один раз.
например, по вашей ссылке: я сейчас пишу с андроида, так вот бета Файерфокс выстрелил алерт два раза, а вебкиты (хром и стандартный) всего по разу. Смахивает на инконсистенс 🙂
так вот бета Файерфокс выстрелил алерт два раза,
у FF(не только бета ) процесс установки размеров фрейма проходит два этапа — дефолтный размер, только затем размер указанный в теге, поэтому можно либо установить frame.onresize с небольшой задержкой, либо запретить срабатывание на время 10-20ms
Второе: — Ширина/высота может изменяться медленно и динамически, поэтому применяется такой приём:
Что убирает слишком частые срабатывания при долгих и плавных или рывковых изменениях размера;
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:
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:
JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
I’m using JQuery as such:
However, it appears that if the person manually resizes their browser windows by dragging the window edge to make it larger/smaller, the .resize event above fires multiple times.
Question: How to I call a function AFTER the browser window resize completed (so that the event only fires once)?
12 Answers 12
Here’s a modification of CMS’s solution that can be called in multiple places in your code:
CMS’s solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.
With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.
I prefer to create an event:
Here is how you create it:
You could have this in a global javascript file somewhere.
I use the following function for delaying repeated actions, it will work for your case:
The callback function passed to it, will execute only when the last call to delay has been made after the specified amount of time, otherwise a timer will be reset, I find this useful for other purposes like detecting when the user stopped typing, etc.
If you have Underscore.js installed, you could:
Some of the previously mentioned solutions did not work for me, even though they are of more general usage. Alternatively I’ve found this one that did the job on window resize:
Many thanks to David Walsh, here is a vanilla version of underscore debounce.
Actually, as I know, you can’t do some actions exactly when resize is off, simply because you don’t know future user’s actions. But you can assume the time passed between two resize events, so if you wait a little more than this time and no resize is made, you can call your function.
Idea is that we use setTimeout and it’s id in order to save or delete it. For example we know that time between two resize events is 500ms, therefore we will wait 750ms.
Declare globally delayed listener:
And below use listeners to resized event as you want:
Cross-browser window resize event — JavaScript / jQuery
What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?
And can you turn both scrollbars on/off?
11 Answers 11
jQuery has a built-in method for this:
For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:
Here is the non-jQuery way of tapping into the resize event:
It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.
Sorry to bring up an old thread, but if someone doesn’t want to use jQuery you can use this:
Since you are open to jQuery, this plugin seems to do the trick.
Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
while this worked in both browsers:
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.
jQuery provides $(window).resize() function by default:
I consider the jQuery plugin «jQuery resize event» to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It’s similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it’s perfect.