- jQuery метод .scroll()
- Определение и применение
- jQuery синтаксис:
- Добавлен в версии jQuery
- Значения параметров
- Пример использования
- More efficient way to handle $(window).scroll functions in jquery?
- 5 Answers 5
- How can I determine the direction of a jQuery scroll event?
- 25 Answers 25
- Existing Solution
- Multi Browser Test
- Combined Solution
- .scroll()
- .scroll( handler ) Returns: jQuery
- version added: 1.0 .scroll( handler )
- version added: 1.4.3 .scroll( [eventData ], handler )
- version added: 1.0 .scroll()
- Additional Notes:
- Example:
- how to get full window height when there is a scroll bar?
- 6 Answers 6
- Not the answer you’re looking for? Browse other questions tagged jquery or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
jQuery метод .scroll()
Определение и применение
jQuery метод .scroll() привязывает JavaScript обработчик событий «scroll» (срабатывает при прокрутке элементов), или запускает это событие на выбранный элемент.
Обратите внимание на то, что событие «scroll» посылается, когда изменяется положение прокрутки элемента, независимо от причины, будь-то щелчок мыши на полосе прокрутки, или перетаскивание полосы прокрутки, перетаскивание внутри элемента, при нажатии клавиш со стрелками, или перемещение с помощью колеса мыши.
Событие «scroll» допускается устанавливать не только на объект window , но и на фреймах (элементы ), элементах, свойство overflow которых установлено в scroll , или в auto , когда высота, или ширина элемента меньше, чем высота, или ширина его содержимого.
jQuery синтаксис:
Обращаю Ваше внимание, что метод .scroll(), используемый вместе с функцией, переданной в качестве параметра (handler) является, короткой записью метода .on(), а без параметра является короткой записью метода .trigger():
Добавлен в версии jQuery
Значения параметров
Параметр | Описание |
---|---|
eventData | Объект, содержащий данные, которые будут переданы в обработчик событий. |
handler | Функция, которая будет выполнена каждый раз, когда событие срабатывает. Функция в качестве параметра может принимать объект Event . |
Пример использования
В этом примере с использованием jQuery метода .scroll() мы при нажатии на элемент (кнопка) вызываем событие «scroll» на элементе
Обратите внимание, что эффект .fadeOut() устанавливает по завершению элементу свойство display в значение none (элемент не отображается), по этой причине мы каждый раз устанавливаем, что элемент должен быть строковый, для его отображения при следующем срабатывании события «scroll». При изменении положения прокрутки элемента
Результат нашего примера:
Пример использования jQuery метода .scroll() (без параметров и с функцией) jQuery события
More efficient way to handle $(window).scroll functions in jquery?
In the code below, I’m checking to see if the window is being scrolled past a certain point and if it is, change an element to use fixed position so that it doesn’t scroll off the top of the page. The only problem is that is seems to be HIGHLY client-side-memory intensive (and really bogs down the scrolling speed) because at every single scroll pixel I am updating the style attributes over and over on the element.
Would checking if the attr is already there before attempting to update it make a significant difference? Is there a completely different and more efficient practice to get the same result?
As I’m typing this, I notice that StackOverflow.com using the same type of functionality with their yellow «Similar Questions» and «Help» menus on the right hand side of this page. I wonder how they do it.
5 Answers 5
One technique you can use is to set a timer on the scroll event and only do the main work when the scroll position hasn’t changed for a short period of time. I use that technique on resize events which have the same issue. You can experiment with what timeout value seems to work right. A shorter time updates with shorter pauses in scrolling and thus may run more often during the scroll, a longer time requires the user to actually pause all motion for a meaningful time. You will have to experiment with what timeout value works best for your purposes and it would be best to test on a relatively slow computer since that’s where the issue of scroll lag would be most pronounced.
Here’s the general idea how this could be implemented:
You may also be able to speed up your scroll function by caching some of the selectors when the scrolling first starts so they don’t have to be recalculated each time. This is one place where the extra overhead of creating a jQuery object each time might not be helping you.
Here’s a jQuery add-on method that handles the scrolling timer for you:
Your code would then be implemented like this:
How can I determine the direction of a jQuery scroll event?
I’m looking for something to this effect:
25 Answers 25
Check current scrollTop vs previous scrollTop
You can do it without having to keep track of the previous scroll top, as all the other examples require:
I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll , the event being listened for is a ‘scroll’ event.
But if you specifically listen for a mousewheel event by using bind, the originalEvent attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta . If it’s positive, you moved the mousewheel up. If it’s negative, you moved the mousewheel down.
My guess is that mousewheel events will fire when the mouse wheel turns, even if the page does not scroll; a case in which ‘scroll’ events probably are not fired. If you want, you can call event.preventDefault() at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.
Store the previous scroll location, then see if the new one is greater than or less than that.
Here’s a way to avoid any global variables (fiddle available here):
Existing Solution
There could be 3 solution from this posting and other answer.
Multi Browser Test
I couldn’t tested it on Safari
chrome 42 (Win 7)
- Solution 1
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
- Solution 2
- Up : Not working
- Down : Not working
- Solution 3
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
Firefox 37 (Win 7)
- Solution 1
- Up : 20 events per 1 scroll
- Down : 20 events per 1 scroll
- Solution 2
- Up : Not working
- Down : 1 event per 1 scroll
- Solution 3
- Up : Not working
- Down : Not working
- Solution 1
- Up : 10 events per 1 scroll (side effect : down scroll occured at last)
- Down : 10 events per 1 scroll
- Solution 2
- Up : Not working
- Down : Not working
- Solution 3
- Up : Not working
- Down : 1 event per 1 scroll
- Solution 1
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
- Solution 2
- Up : Not working
- Down : Not working
- Solution 3
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
- Solution 1
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
- Solution 2
- Up : Not working
- Down : Not working
- Solution 3
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
- Solution 1
- Up : 2 events per 1 scroll (side effect : down scroll occured at last)
- Down : 2
4 events per 1 scroll
- Up : Not working
- Down : Not working
- Up : 1 event per 1 scroll
- Down : 1 event per 1 scroll
Combined Solution
I checked that side effect from IE 11 and IE 8 is come from if else statement. So, I replaced it with if else if statement as following.
From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.
.scroll()
.scroll( handler ) Returns: jQuery
Description: Bind an event handler to the «scroll» JavaScript event, or trigger that event on an element.
version added: 1.0 .scroll( handler )
version added: 1.4.3 .scroll( [eventData ], handler )
version added: 1.0 .scroll()
This method is a shortcut for .on( «scroll», handler ) in the first and second variations, and .trigger( «scroll» ) in the third.
The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element’s explicit height or width is less than the height or width of its contents).
For example, consider the HTML:
The style definition is present to make the target element small enough to be scrollable:
Figure 1 — Illustration of the rendered HTML
The scroll event handler can be bound to this element:
Now when the user scrolls the text up or down, one or more messages are appended to
Handler for .scroll() called.
To trigger the event manually, apply .scroll() without an argument:
After this code executes, clicks on Trigger the handler will also append the message.
A scroll event is sent whenever the element’s scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse’s scroll wheel could cause this event.
Additional Notes:
- As the .scroll() method is just a shorthand for .on( «scroll», handler ) , detaching is possible using .off( «scroll» ) .
Example:
To do something when your page is scrolled:
how to get full window height when there is a scroll bar?
var window_height = $( window ).height(); this is giving current window height not the full height including scroll height. I want full window height including scroll height.
6 Answers 6
As of 2020 the best way to find the height of an entire document is:
Credit: this answer on another question.
None of the above worked for me — all gave viewport-height. I had to wrap the entire page in a div (class ‘wrapper’), then get it with:
Use $(document).height(); to get full height with scrollable area.
Use $(window).height(); to get only viewable area height.
Important : The document height is the entire height of the whole document, even what is outside the viewable area. The window height is just the viewable area.
Not the answer you’re looking for? Browse other questions tagged jquery or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.