Javascript определить ширину экрана

Window sizes and scrolling

How do we find the width and height of the browser window? How do we get the full width and height of the document, including the scrolled out part? How do we scroll the page using JavaScript?

For this type of information, we can use the root document element document.documentElement , that corresponds to the tag. But there are additional methods and peculiarities to consider.

Width/height of the window

To get window width and height, we can use the clientWidth/clientHeight of document.documentElement :

For instance, this button shows the height of your window:

Browsers also support properties like window.innerWidth/innerHeight . They look like what we want, so why not to use them instead?

If there exists a scrollbar, and it occupies some space, clientWidth/clientHeight provide the width/height without it (subtract it). In other words, they return the width/height of the visible part of the document, available for the content.

window.innerWidth/innerHeight includes the scrollbar.

If there’s a scrollbar, and it occupies some space, then these two lines show different values:

alert( window.innerWidth ); // full window width alert( document.documentElement.clientWidth ); // window width minus the scrollbar

In most cases, we need the available window width in order to draw or position something within scrollbars (if there are any), so we should use documentElement.clientHeight/clientWidth .

Please note: top-level geometry properties may work a little bit differently when there’s no in HTML. Odd things are possible.

In modern HTML we should always write DOCTYPE .

Width/height of the document

Theoretically, as the root document element is document.documentElement , and it encloses all the content, we could measure the document’s full size as document.documentElement.scrollWidth/scrollHeight .

But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera, if there’s no scroll, then documentElement.scrollHeight may be even less than documentElement.clientHeight ! Weird, right?

To reliably obtain the full document height, we should take the maximum of these properties:

let scrollHeight = Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ); alert('Full document height, with scrolled out part: ' + scrollHeight);

Why so? Better don’t ask. These inconsistencies come from ancient times, not a “smart” logic.

Get the current scroll

DOM elements have their current scroll state in their scrollLeft/scrollTop properties.

Читайте также:  Python что делает round

For document scroll, document.documentElement.scrollLeft/scrollTop works in most browsers, except older WebKit-based ones, like Safari (bug 5991), where we should use document.body instead of document.documentElement .

Luckily, we don’t have to remember these peculiarities at all, because the scroll is available in the special properties, window.pageXOffset/pageYOffset :

alert('Current scroll from the top: ' + window.pageYOffset); alert('Current scroll from the left: ' + window.pageXOffset);

These properties are read-only.

For historical reasons, both properties exist, but they are the same:

  • window.pageXOffset is an alias of window.scrollX .
  • window.pageYOffset is an alias of window.scrollY .

Scrolling: scrollTo, scrollBy, scrollIntoView

To scroll the page with JavaScript, its DOM must be fully built.

For instance, if we try to scroll the page with a script in , it won’t work.

Regular elements can be scrolled by changing scrollTop/scrollLeft .

We can do the same for the page using document.documentElement.scrollTop/scrollLeft (except Safari, where document.body.scrollTop/Left should be used instead).

Alternatively, there’s a simpler, universal solution: special methods window.scrollBy(x,y) and window.scrollTo(pageX,pageY).

  • The method scrollBy(x,y) scrolls the page relative to its current position. For instance, scrollBy(0,10) scrolls the page 10px down. The button below demonstrates this: window.scrollBy(0,10)
  • The method scrollTo(pageX,pageY) scrolls the page to absolute coordinates, so that the top-left corner of the visible part has coordinates (pageX, pageY) relative to the document’s top-left corner. It’s like setting scrollLeft/scrollTop . To scroll to the very beginning, we can use scrollTo(0,0) . window.scrollTo(0,0)

These methods work for all browsers the same way.

scrollIntoView

For completeness, let’s cover one more method: elem.scrollIntoView(top).

The call to elem.scrollIntoView(top) scrolls the page to make elem visible. It has one argument:

  • If top=true (that’s the default), then the page will be scrolled to make elem appear on the top of the window. The upper edge of the element will be aligned with the window top.
  • If top=false , then the page scrolls to make elem appear at the bottom. The bottom edge of the element will be aligned with the window bottom.

The button below scrolls the page to position itself at the window top:

And this button scrolls the page to position itself at the bottom:

Forbid the scrolling

Sometimes we need to make the document “unscrollable”. For instance, when we need to cover the page with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document.

To make the document unscrollable, it’s enough to set document.body.style.overflow = «hidden» . The page will “freeze” at its current scroll position.

Читайте также:  Date in python times

The first button freezes the scroll, while the second one releases it.

We can use the same technique to freeze the scroll for other elements, not just for document.body .

The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free and the content “jumps” to fill it.

That looks a bit odd, but can be worked around if we compare clientWidth before and after the freeze. If it increased (the scrollbar disappeared), then add padding to document.body in place of the scrollbar to keep the content width the same.

Summary

  • Width/height of the visible part of the document (content area width/height): document.documentElement.clientWidth/clientHeight
  • Width/height of the whole document, with the scrolled out part:
let scrollHeight = Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight );
  • Read the current scroll: window.pageYOffset/pageXOffset .
  • Change the current scroll:
    • window.scrollTo(pageX,pageY) – absolute coordinates,
    • window.scrollBy(x,y) – scroll relative the current place,
    • elem.scrollIntoView(top) – scroll to make elem visible (align with the top/bottom of the window).

    Источник

    Как получить размеры экрана, окна и веб-страницы в JavaScript?

    Представляю Вашему вниманию перевод небольшой заметки «How to Get the Screen, Window, and Web Page Sizes in JavaScript» автора Dmitri Pavlutin.

    Для определения ориентации окна браузера (ландшафтной или портретной) можно сравнить его ширину и высоту.

    Однако во всевозможных доступных размерах легко запутаться: существуют размеры экрана, окна, веб-страницы и т.д.

    Что означают эти размеры и, главное, как их получить? Именно об этом я и собираюсь рассказать.

    1. Экран

    1.1. Размер экрана

    Размер экрана — это ширина и высота всего экрана: монитора или мобильного дисплея.

    Получить информацию о размере экрана можно с помощью свойства screen объекта window :

    const screenWidth = window.screen.width const screenHeight = window.screen.height 
    1.2. Доступный размер экрана

    Доступный размер экрана — это ширина и высота активного экрана без панели инструментов операционной системы.

    Для получения доступного размера экрана снова обращаемся к window.screen :

    const availableScreenWidth = window.screen.availWidth const availableScreenHeight = window.screen.availHeight 

    2. Окно

    2.1. Размер внешнего окна (или внешний размер окна)

    Размер внешнего окна — это ширина и высота текущего окна браузера, включая адресную строку, панель вкладок и другие панели браузера.

    Получить информацию о размере внешнего окна можно с помощью свойств outerWidth и outerHeight объекта window :

    const windowOuterWidth = window.outerWidth const windowOuterHeight = window.outerHeight 
    2.2. Внутренний размер окна (или размер внутреннего окна)

    Внутренний размер окна — это ширина и высота области просмотра (вьюпорта).

    Объект window предоставляет свойства innerWidth и innerHeight :

    const windowInnerWidth = window.innerWidth const windowInnerHeight = window.innerHeight 

    Если мы хотим получить внутренний размер окна без полос прокрутки, то делаем следующее:

    const windowInnerWidth = document.documentElement.clientWidth const windowInnerHeight = document.documentElement.clientHeight 

    3. Размер веб-страницы

    Размер веб-страницы — это ширина и высота отображаемого содержимого (отрендеренного контента).

    Для получения размера веб-страницы используйте следующее (включает в себя внутренние отступы страницы, но не включает границы, внешние отступы и полосы прокрутки):

    const pageWidth = document.documentElement.scrollWidth const pageHeight = document.documentElement.scrollHeight 

    Если pageHeight больше, чем внутренняя высота окна, значит, присутствует вертикальная полоса прокрутки.

    4. Заключение

    Надеюсь, теперь Вы понимаете, как получать различные размеры.

    Размер экрана — это размер монитора (или дисплея), а доступный размер экрана — это размер экрана без панелей инструментов ОС.

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

    Наконец, размер веб-страницы — это размер контента.

    Благодарю за внимание, друзья!

    Источник

    Window: innerWidth property

    The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

    More precisely, innerWidth returns the width of the window’s layout viewport. The interior height of the window—the height of the layout viewport—can be obtained from the innerHeight property.

    Value

    An integer value indicating the width of the window’s layout viewport in pixels. This property is read-only, and has no default value.

    To change the window’s width, use one of the Window methods for resizing windows, such as resizeBy() or resizeTo() .

    Usage notes

    If you need to obtain the width of the window minus the scrollbar and borders, use the root element’s clientWidth property instead.

    The innerWidth property is available on any window or object that behaves like a window, such as a frame or tab.

    Examples

    // This will log the width of the viewport console.log(window.innerWidth); // This will log the width of the frame viewport within a frameset console.log(self.innerWidth); // This will log the width of the viewport of the closest frameset console.log(parent.innerWidth); // This will log the width of the viewport of the outermost frameset console.log(top.innerWidth); 

    Demo

    HTML

    p>Resize the browser window to fire the code>resizecode> event.p> p>Window height: span id="height">span>p> p>Window width: span id="width">span>p> 

    JavaScript

    const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function updateSize()  heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; > updateSize(); window.addEventListener("resize", updateSize); 

    Result

    Specifications

    Источник

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