- Обработчик или источник события resize
- Материал из JQuery
- jQuery метод .resize()
- Определение и применение
- jQuery синтаксис:
- Добавлен в версии jQuery
- Значения параметров
- Пример использования
- Cross-browser window resize event - JavaScript / jQuery
- 11 Answers 11
- jQuery on window resize
- 9 Answers 9
- javascript
- jQuery
- How do I stop my resize code from executing so often!?
- JavaScript window resize event
- 13 Answers 13
Обработчик или источник события resize
Материал из JQuery
Устанавливает функцию handler в качестве обработчика события resize, на выбранные элементы.
Метод является аналогом bind("resize", handler(eventObject)).
handler(eventObject) — функция, которая будет установлена в качестве обработчика. При вызове она будет получать объект события eventObject.
Метод отличается от предыдущего возможностью передавать в обработчик дополнительные данные.
Является аналогом bind("resize", eventData, handler(eventObject)).
handler(eventObject) — см. выше.
eventData — дополнительные данные, передаваемые в обработчик. Они должны быть представлены объектом в формате: .
Вызывает событие resize, у выбранных элементов страницы. Метод является аналогом trigger("resize").
Убрать установленный обработчик можно с помощью метода unbind().
Все три варианта использования метода, являются аналогами других методов (см. выше), поэтому все подробности использования resize(), можно найти в описании этих методов.
Следует помнить, что в различных браузерах событие resize вызывается разное количество раз. В IE и браузерах на основе WebKit (Safari и Chrome) это событие вызывается постоянно по мере изменения размеров окна, в то время как в других браузерах (особенно в Firefox), событие resize может быть вызвано только при завершении изменения размеров окна.
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 события
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.
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:
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: