CINXE.COM
<!DOCTYPE html><html lang="tr" data-theme-enabled="1"><head><script>window.currentUser = null;</script><script>window.shopCurrency = "EUR";</script><script>window.localCurrency = "TRY";</script><script>window.countryCode = "ph";</script><script>window.rateShopTo = {"TRY":41.094711407235664,"EUR":1,"USD":1.0874494200088518,"AMD":424.1827578369761};</script><title itemprop="name">Coordinates</title><link href="/pack/styles.100020a0bc7cf13be729.css" rel="stylesheet"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1.0"><meta name="apple-mobile-web-app-capable" content="yes"><!-- chrome autotranslate is enabled only for "en" main version--><meta name="google" content="notranslate"><script>if (window.devicePixelRatio > 1) document.cookie = 'pixelRatio=' + window.devicePixelRatio + ';path=/;expires=Tue, 19 Jan 2038 03:14:07 GMT';</script><link href="//fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic" rel="stylesheet"><link rel="apple-touch-icon-precomposed" href="/img/favicon/apple-touch-icon-precomposed.png"><link rel="canonical" href="https://tr.javascript.info/coordinates"><meta name="msapplication-TileColor" content="#222A2C"><meta name="msapplication-TileImage" content="/img/favicon/tileicon.png"><link rel="icon" href="/img/favicon/favicon.png"><meta itemprop="image" content="https://tr.javascript.info/img/site_preview_en_512x512.png"><meta property="og:title" content="Coordinates"><meta property="og:image" content="https://tr.javascript.info/img/site_preview_en_1200x630.png"><meta property="og:image:type" content="image/png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta property="fb:admins" content="100001562528165"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Coordinates"><meta name="twitter:site" content="@iliakan"><meta name="twitter:creator" content="@iliakan"><meta name="twitter:image" content="https://tr.javascript.info/img/site_preview_en_512x512.png"><meta name="google-adsense-account" content="ca-pub-6204518652652613"><link rel="prev" href="/size-and-scroll-window"><link rel="next" href="/events"><script data-collect-dnt="true" async src="https://scripts.simpleanalyticscdn.com/latest.js"></script><script>window.GA_ID = "UA-2056213-15";</script><script>window.YANDEX_METRIKA_ID = 32184394;</script><script>{function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","G-2LWB61WGYJ")}</script> <script async src="https://www.googletagmanager.com/gtag/js?id=G-2LWB61WGYJ"></script><script>window.metrika={reachGoal:function(){}},window.yandex_metrika_callbacks=[function(){try{window.metrika=new Ya.Metrika({id:YANDEX_METRIKA_ID,webvisor:!0,clickmap:!0,params:{user:window.currentUser&&window.currentUser.id}}),metrika.trackLinks({delay:150}),window.addEventListener("error",function(r){window.metrika.reachGoal("JSERROR",{src:(r.filename||r.errorUrl)+": "+(r.lineno||r.errorLine),stack:r.stack||r.error&&r.error.stack,message:r.message})})}catch(r){}}];</script><script src="//mc.yandex.ru/metrika/watch.js" async></script><script>window.RECAPTCHA_ID = "6LfmLAEVAAAAAJMykMnf7aY8nkyTRmYi2ynx51R1";</script><script src="/pack/init.6423bccabee4f56b6ff8.js"></script><script src="/pack/head.fb50118fab5c8ea51243.js" defer></script><script> document.addEventListener('DOMContentLoaded', function() { let elem = document.getElementById('coords-show-mark'); // no elem in ebook mode if (elem) { elem.onclick = function() { function createMessageUnder(elem, text) { let coords = elem.getBoundingClientRect(); let message = document.createElement('div'); message.style.cssText = "position:fixed; color: red"; message.style.left = coords.left + "px"; message.style.top = coords.bottom + "px"; message.innerHTML = text; return message; } let message = createMessageUnder(elem, 'Hello, world!'); document.body.append(message); setTimeout(() => message.remove(), 5000); } } }); </script> <meta property="og:title" content="Coordinates"><meta property="og:type" content="article"><script src="/pack/tutorial.ba5237b93f596f9d03dc.js" defer></script><script src="/pack/footer.59b83436a1264feec8f6.js" defer></script></head><body class="no-icons"><script>window.fontTest();</script><div class="page-wrapper page-wrapper_sidebar_on"><!--[if IE]><div style="color:red;text-align:center">Üzgünüz, Internet Explorer desteklenmemektedi lütfen daha yeni bir tarayıcı kullanın.</div><![endif]--><div class="sitetoolbar sitetoolbar_tutorial"><script>window.langs = [{"code":"ar","name":"Arabic"},{"code":"az","name":"Azerbaijani"},{"code":"bg","name":"Bulgarian"},{"code":"bn","name":"Bengali"},{"code":"bs","name":"Bosnian"},{"code":"ca","name":"Catalan"},{"code":"cs","name":"Czech"},{"code":"da","name":"Danish"},{"code":"de","name":"German"},{"code":"el","name":"Greek"},{"code":"en","name":"English"},{"code":"es","name":"Spanish"},{"code":"fa","name":"Persian (Farsi)"},{"code":"fi","name":"Finnish"},{"code":"fr","name":"French"},{"code":"he","name":"Hebrew"},{"code":"hi","name":"Hindi"},{"code":"hr","name":"Croatian"},{"code":"hu","name":"Hungarian"},{"code":"hy","name":"Armenian"},{"code":"id","name":"Indonesian"},{"code":"it","name":"Italian"},{"code":"ja","name":"Japanese"},{"code":"ka","name":"Georgian"},{"code":"kk","name":"Kazakh"},{"code":"km","name":"Central Khmer"},{"code":"ko","name":"Korean"},{"code":"ku","name":"Kurdish"},{"code":"ky","name":"Kyrgyz"},{"code":"lt","name":"Lithuanian"},{"code":"me","name":"Montenegrin"},{"code":"ml","name":"Malayalam"},{"code":"ms","name":"Malay"},{"code":"my","name":"Burmese"},{"code":"nl","name":"Dutch"},{"code":"no","name":"Norvegian"},{"code":"pa","name":"Punjabi"},{"code":"pl","name":"Polish"},{"code":"pt","name":"Portuguese"},{"code":"ro","name":"Romanian"},{"code":"ru","name":"Russian"},{"code":"si","name":"Sinhala"},{"code":"sk","name":"Slovak"},{"code":"sl","name":"Slovenian"},{"code":"sq","name":"Albanian"},{"code":"sr","name":"Serbian"},{"code":"ta","name":"Tamil"},{"code":"te","name":"Telugu"},{"code":"test","name":"Test"},{"code":"th","name":"Thai"},{"code":"tk","name":"Turkmen"},{"code":"tr","name":"Turkish"},{"code":"ug","name":"Uyghur"},{"code":"uk","name":"Ukrainian"},{"code":"ur","name":"Urdu"},{"code":"uz","name":"Uzbek"},{"code":"v2","name":"v2"},{"code":"vi","name":"Vietnamese"},{"code":"zh-hant","name":"Chinese Traditional"},{"code":"zh","name":"Chinese"}];</script><script>window.lang = "tr";</script><div class="sitetoolbar__content"><div class="sitetoolbar__lang-switcher"><button class="sitetoolbar__dropdown-button" data-dropdown-toggler>TR</button><div class="sitetoolbar__dropdown-wrap"><div class="sitetoolbar__dropdown-body"><div class="sitetoolbar__lang-switcher-body"><div class="supported-langs supported-langs_toolbar"><div class="supported-langs__container"><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://ar.javascript.info/coordinates"><span class="supported-langs__brief">AR</span><span class="supported-langs__title">عربي</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://javascript.info/coordinates"><span class="supported-langs__brief">EN</span><span class="supported-langs__title">English</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://es.javascript.info/coordinates"><span class="supported-langs__brief">ES</span><span class="supported-langs__title">Español</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fa.javascript.info/"><span class="supported-langs__brief">FA</span><span class="supported-langs__title">فارسی</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fr.javascript.info/coordinates"><span class="supported-langs__brief">FR</span><span class="supported-langs__title">Français</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://id.javascript.info/"><span class="supported-langs__brief">ID</span><span class="supported-langs__title">Indonesia</span></a></li></ul><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://it.javascript.info/coordinates"><span class="supported-langs__brief">IT</span><span class="supported-langs__title">Italiano</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ja.javascript.info/coordinates"><span class="supported-langs__brief">JA</span><span class="supported-langs__title">日本語</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ko.javascript.info/coordinates"><span class="supported-langs__brief">KO</span><span class="supported-langs__title">한국어</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://learn.javascript.ru/coordinates"><span class="supported-langs__brief">RU</span><span class="supported-langs__title">Русский</span></a></li><li class="supported-langs__item supported-langs__item_current"><a class="supported-langs__link" href="https://tr.javascript.info/coordinates"><span class="supported-langs__brief">TR</span><span class="supported-langs__title">Türkçe</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://uk.javascript.info/coordinates"><span class="supported-langs__brief">UK</span><span class="supported-langs__title">Українська</span></a></li></ul><ul class="supported-langs__list" style="height:20px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://zh.javascript.info/coordinates"><span class="supported-langs__brief">ZH</span><span class="supported-langs__title">简体中文</span></a></li></ul></div><div class="supported-langs__text"><p>Bu açık-kaynaklı projenin tüm dünyada kullanılabilir olmasını istiyoruz.</p> <p>Kendi dilinizde çeviriye <a href="https://javascript.info/translate">yardım edebilirsiniz</a>!</p> </div></div></div></div></div></div><div class="sitetoolbar__logo-wrap"><a class="sitetoolbar__link sitetoolbar__link_logo" href="/"><img class="sitetoolbar__logo sitetoolbar__logo_normal" src="/img/sitetoolbar__logo_en.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_normal sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_en-white.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small" src="/img/sitetoolbar__logo_small_en.svg" width="70" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_small_en-white.svg" width="70" alt="" role="presentation"/><script>Array.prototype.forEach.call(document.querySelectorAll("img.sitetoolbar__logo"),function(e){let t=document.createElement("object");t.type="image/svg+xml",t.className=e.className,t.style.cssText="left:0;top:0;position:absolute",t.onload=function(){t.onload=null,e.style.visibility="hidden"},t.data=e.src,e.parentNode.insertBefore(t,e)});</script></a></div><div class="sitetoolbar__nav-toggle-wrap"><button class="sitetoolbar__nav-toggle" type="button"></button></div><nav class="sitetoolbar__sections"><ul class="sitetoolbar__sections-list"></ul></nav><div class="sitetoolbar__right-button-wrap"><a class="sitetoolbar-right-button sitetoolbar-right-button_courses" href="/ebook"><span class="sitetoolbar-right-button__extra-text">Satın al</span>EPUB/PDF</a></div><div class="sitetoolbar__theme-switcher"><div class="theme-changer"><label class="theme-changer__label" for="theme-changer-input" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span></label></div></div><div class="sitetoolbar__search-wrap"><div class="sitetoolbar__search-content"><button class="sitetoolbar__search-toggle" type="button"></button><form class="sitetoolbar__search" method="GET" action="/search"><div class="sitetoolbar__search-input"><div class="text-input"><input class="text-input__control" name="query" placeholder="Javascript.info'da ara" required="required" type="text"/></div><button class="sitetoolbar__find" type="submit">Ara</button></div></form></div></div></div><div class="tablet-menu"><div class="tablet-menu__line"><div class="tablet-menu__content"><form class="tablet-menu-search" action="/search/"><input class="tablet-menu-search__input" type="search" name="query" placeholder="Eğitimde ara" required="required"/><button class="tablet-menu-search__button" type="submit" name="type" value="articles">Ara</button></form></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Eğitim haritası</span></a></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="theme-changer theme-changer_tablet-menu theme-changer_has-label"><label class="theme-changer__label" for="theme-changer-input-tablet" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input-tablet" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span><span class="theme-changer__label-text theme-changer__label-text_light-theme">Light theme</span><span class="theme-changer__label-text theme-changer__label-text_dark-theme">Dark theme</span></label></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="share-icons"><span class="share-icons__title">Paylaş</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&p%5Burl%5D=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><select class="tablet-menu__nav input-select input-select input-select_small" onchange="if(this.value) window.location.href=this.value"><option value="https://ar.javascript.info/coordinates">عربي</option><option value="https://javascript.info/coordinates">English</option><option value="https://es.javascript.info/coordinates">Español</option><option value="https://fa.javascript.info/">فارسی</option><option value="https://fr.javascript.info/coordinates">Français</option><option value="https://id.javascript.info/">Indonesia</option><option value="https://it.javascript.info/coordinates">Italiano</option><option value="https://ja.javascript.info/coordinates">日本語</option><option value="https://ko.javascript.info/coordinates">한국어</option><option value="https://learn.javascript.ru/coordinates">Русский</option><option value="https://tr.javascript.info/coordinates" selected>Türkçe</option><option value="https://uk.javascript.info/coordinates">Українська</option><option value="https://zh.javascript.info/coordinates">简体中文</option></select></div></div></div><progress class="tutorial-progress" data-sticky value="11" max="30" data-tooltip="30'in 11'i dersi"></progress></div><div class="page page_sidebar_on page_inner_padding"><script>if(localStorage.noSidebar){document.querySelector(".page").classList.remove("page_sidebar_on");let e=document.querySelector(".page-wrapper");e&&e.classList.remove("page-wrapper_sidebar_on")}setTimeout(function(){document.querySelector(".page").classList.add("page_sidebar-animation-on")});</script><div class="page__inner"><main class="main main_width-limit"><header class="main__header"><div class="main__header-inner"><div class="main__header-group"><ol class="breadcrumbs"><li class="breadcrumbs__item breadcrumbs__item_home"><a class="breadcrumbs__link" href="/"><span class="breadcrumbs__hidden-text">Eğitim</span></a></li><li class="breadcrumbs__item" id="breadcrumb-1"><a class="breadcrumbs__link" href="/ui"><span>Browser: Document, Events, Interfaces</span></a></li><li class="breadcrumbs__item" id="breadcrumb-2"><a class="breadcrumbs__link" href="/document"><span>Document</span></a></li><script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Eğitim","item":"https://tr.javascript.info/"},{"@type":"ListItem","position":2,"name":"Browser: Document, Events, Interfaces","item":"https://tr.javascript.info/ui"},{"@type":"ListItem","position":3,"name":"Document","item":"https://tr.javascript.info/document"}]}</script></ol><div class="updated-at" data-tooltip="Son güncelleme 5 Nisan 2019"><div class="updated-at__content">5 Nisan 2019</div></div></div><h1 class="main__header-title">Coordinates</h1></div></header><div class="content"><article class="formatted" itemscope itemtype="http://schema.org/TechArticle"><meta itemprop="name" content="Coordinates"><div itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="email" content="iliakan@gmail.com"><meta itemprop="name" content="Ilya Kantor"></div><div itemprop="articleBody"><p>To move elements around we should be familiar with coordinates.</p> <p>Most JavaScript methods deal with one of two coordinate systems:</p> <ol> <li>Relative to the window(or another viewport) top/left.</li> <li>Relative to the document top/left.</li> </ol> <p>It’s important to understand the difference and which type is where.</p> <h2><a class="main__anchor" name="window-coordinates-getboundingclientrect" href="#window-coordinates-getboundingclientrect">Window coordinates: getBoundingClientRect</a></h2><p>Window coordinates start at the upper-left corner of the window.</p> <p>The method <code>elem.getBoundingClientRect()</code> returns window coordinates for <code>elem</code> as an object with properties:</p> <ul> <li><code>top</code> – Y-coordinate for the top element edge,</li> <li><code>left</code> – X-coordinate for the left element edge,</li> <li><code>right</code> – X-coordinate for the right element edge,</li> <li><code>bottom</code> – Y-coordinate for the bottom element edge.</li> </ul> <p>Like this:</p> <figure><div class="image" style="width:501px"> <div class="image__ratio" style="padding-top:77.04590818363273%"></div> <img src="/article/coordinates/coords.png" alt="" width="501" height="386" class="image__image"> </div></figure><p>Window coordinates do not take the scrolled out part of the document into account, they are calculated from the window’s upper-left corner.</p> <p>In other words, when we scroll the page, the element goes up or down, <em>its window coordinates change</em>. That’s very important.</p> <p>Click the button to see its window coordinates:</p> <input id="brTest" type="button" value="Show button.getBoundingClientRect() for this button" onclick='showRect(this)'/> <script> function showRect(elem) { let r = elem.getBoundingClientRect(); alert("{top:"+r.top+", left:"+r.left+", right:"+r.right+", bottom:"+ r.bottom + "}"); } </script> <p>If you scroll the page, the button position changes, and window coordinates as well.</p> <p>Also:</p> <ul> <li>Coordinates may be decimal fractions. That’s normal, internally browser uses them for calculations. We don’t have to round them when setting to <code>style.position.left/top</code>, the browser is fine with fractions.</li> <li>Coordinates may be negative. For instance, if the page is scrolled down and the top <code>elem</code> is now above the window. Then, <code>elem.getBoundingClientRect().top</code> is negative.</li> <li>Some browsers (like Chrome) provide additional properties, <code>width</code> and <code>height</code> of the element that invoked the method to <code>getBoundingClientRect</code> as the result. We can also get them by subtraction: <code>height=bottom-top</code>, <code>width=right-left</code>.</li> </ul> <div class="important important_warn"> <div class="important__header"><span class="important__type">Coordinates right/bottom are different from CSS properties</span></div> <div class="important__content"><p>If we compare window coordinates versus CSS positioning, then there are obvious similarities to <code>position:fixed</code>. The positioning of an element is also relative to the viewport.</p> <p>But in CSS, the <code>right</code> property means the distance from the right edge, and the <code>bottom</code> property means the distance from the bottom edge.</p> <p>If we just look at the picture above, we can see that in JavaScript it is not so. All window coordinates are counted from the upper-left corner, including these ones.</p> </div></div> <h2><a class="main__anchor" name="elementFromPoint" href="#elementFromPoint">elementFromPoint(x, y)</a></h2><p>The call to <code>document.elementFromPoint(x, y)</code> returns the most nested element at window coordinates <code>(x, y)</code>.</p> <p>The syntax is:</p> <div id="kj6rzl8tmy" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let elem = document.elementFromPoint(x, y);</code></pre> </div> </div> </div><p>For instance, the code below highlights and outputs the tag of the element that is now in the middle of the window:</p> <div id="calo9dn8pq" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="Çalıştır" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="Korumalı alanda aç" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let centerX = document.documentElement.clientWidth / 2; let centerY = document.documentElement.clientHeight / 2; let elem = document.elementFromPoint(centerX, centerY); elem.style.background = "red"; alert(elem.tagName);</code></pre> </div> </div> </div><p>As it uses window coordinates, the element may be different depending on the current scroll position.</p> <div class="important important_warn"> <div class="important__header"><span class="important__type">For out-of-window coordinates the <code>elementFromPoint</code> returns <code>null</code></span></div> <div class="important__content"><p>The method <code>document.elementFromPoint(x,y)</code> only works if <code>(x,y)</code> are inside the visible area.</p> <p>If any of the coordinates is negative or exceeds the window width/height, then it returns <code>null</code>.</p> <p>In most cases such behavior is not a problem, but we should keep that in mind.</p> <p>Here’s a typical error that may occur if we don’t check for it:</p> <div id="g3cy7jokky" data-trusted="1" class="code-example" data-highlight="[{"start":2,"end":2}]"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let elem = document.elementFromPoint(x, y); // if the coordinates happen to be out of the window, then elem = null elem.style.background = ''; // Error!</code></pre> </div> </div> </div></div></div> <h2><a class="main__anchor" name="using-for-position-fixed" href="#using-for-position-fixed">Using for position:fixed</a></h2><p>Most of time we need coordinates to position something. In CSS, to position an element relative to the viewport we use <code>position:fixed</code> together with <code>left/top</code> (or <code>right/bottom</code>).</p> <p>We can use <code>getBoundingClientRect</code> to get coordinates of an element, and then to show something near it.</p> <p>For instance, the function <code>createMessageUnder(elem, html)</code> below shows the message under <code>elem</code>:</p> <div id="kp1tl85d0m" data-trusted="1" class="code-example" data-highlight="[{"start":8,"end":12}]"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let elem = document.getElementById("coords-show-mark"); function createMessageUnder(elem, html) { // create message element let message = document.createElement('div'); // better to use a css class for the style here message.style.cssText = "position:fixed; color: red"; // assign coordinates, don't forget "px"! let coords = elem.getBoundingClientRect(); message.style.left = coords.left + "px"; message.style.top = coords.bottom + "px"; message.innerHTML = html; return message; } // Usage: // add it for 5 seconds in the document let message = createMessageUnder(elem, 'Hello, world!'); document.body.append(message); setTimeout(() => message.remove(), 5000);</code></pre> </div> </div> </div><p>Click the button to run it:</p> <p><button id="coords-show-mark">Button with id=“coords-show-mark”, the message will appear under it</button></p> <p>The code can be modified to show the message at the left, right, below, apply CSS animations to “fade it in” and so on. That’s easy, as we have all the coordinates and sizes of the element.</p> <p>But note the important detail: when the page is scrolled, the message flows away from the button.</p> <p>The reason is obvious: the message element relies on <code>position:fixed</code>, so it remains at the same place of the window while the page scrolls away.</p> <p>To change that, we need to use document-based coordinates and <code>position:absolute</code>.</p> <h2><a class="main__anchor" name="document-coordinates" href="#document-coordinates">Document coordinates</a></h2><p>Document-relative coordinates start from the upper-left corner of the document, not the window.</p> <p>In CSS, window coordinates correspond to <code>position:fixed</code>, while document coordinates are similar to <code>position:absolute</code> on top.</p> <p>We can use <code>position:absolute</code> and <code>top/left</code> to put something at a certain place of the document, so that it remains there during a page scroll. But we need the right coordinates first.</p> <p>For clarity we’ll call window coordinates <code>(clientX,clientY)</code> and document coordinates <code>(pageX,pageY)</code>.</p> <p>When the page is not scrolled, then window coordinate and document coordinates are actually the same. Their zero points match too:</p> <figure><div class="image" style="width:694px"> <div class="image__ratio" style="padding-top:68.73198847262248%"></div> <img src="/article/coordinates/document-window-coordinates-zero.png" alt="" width="694" height="477" class="image__image"> </div></figure><p>And if we scroll it, then <code>(clientX,clientY)</code> change, because they are relative to the window, but <code>(pageX,pageY)</code> remain the same.</p> <p>Here’s the same page after the vertical scroll:</p> <figure><div class="image" style="width:690px"> <div class="image__ratio" style="padding-top:69.27536231884058%"></div> <img src="/article/coordinates/document-window-coordinates-scroll.png" alt="" width="690" height="478" class="image__image"> </div></figure><ul> <li><code>clientY</code> of the header <code>"From today's featured article"</code> became <code>0</code>, because the element is now on window top.</li> <li><code>clientX</code> didn’t change, as we didn’t scroll horizontally.</li> <li><code>pageX</code> and <code>pageY</code> coordinates of the element are still the same, because they are relative to the document.</li> </ul> <h2><a class="main__anchor" name="getCoords" href="#getCoords">Getting document coordinates</a></h2><p>There’s no standard method to get the document coordinates of an element. But it’s easy to write it.</p> <p>The two coordinate systems are connected by the formula:</p> <ul> <li><code>pageY</code> = <code>clientY</code> + height of the scrolled-out vertical part of the document.</li> <li><code>pageX</code> = <code>clientX</code> + width of the scrolled-out horizontal part of the document.</li> </ul> <p>The function <code>getCoords(elem)</code> will take window coordinates from <code>elem.getBoundingClientRect()</code> and add the current scroll to them:</p> <div id="fcy4z30in0" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>// get document coordinates of the element function getCoords(elem) { let box = elem.getBoundingClientRect(); return { top: box.top + pageYOffset, left: box.left + pageXOffset }; }</code></pre> </div> </div> </div><h2><a class="main__anchor" name="summary" href="#summary">Summary</a></h2><p>Any point on the page has coordinates:</p> <ol> <li>Relative to the window – <code>elem.getBoundingClientRect()</code>.</li> <li>Relative to the document – <code>elem.getBoundingClientRect()</code> plus the current page scroll.</li> </ol> <p>Window coordinates are great to use with <code>position:fixed</code>, and document coordinates do well with <code>position:absolute</code>.</p> <p>Both coordinate systems have their “pro” and “contra”, there are times we need one or the other one, just like CSS <code>position</code> <code>absolute</code> and <code>fixed</code>.</p> </div></article><div class="tasks formatted"><h2 class="tasks__title" id="tasks"><a class="tasks__title-anchor main__anchor main__anchor main__anchor_noicon" href="#tasks">Görevler</a></h2><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#find-window-coordinates-of-the-field" name="find-window-coordinates-of-the-field">Find window coordinates of the field</a></h3><a class="task__open-link" href="/task/find-point-coordinates" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="Görevin önemi 1'den 5'e kadar hangisidir.">önem: 5</span></div><div class="task__content"><div class="task__formatted"><p>In the iframe below you can see a document with the green “field”.</p> <p>Use JavaScript to find window coordinates of corners pointed by with arrows.</p> <p>There’s a small feature implemented in the document for convenience. A click at any place shows coordinates there.</p> <div class="code-result"> <div class="code-result__toolbar toolbar"><div class="toolbar__tool"> <a href="https://tr.js.cx/task/find-point-coordinates/source/" target="_blank" title="yeni pencerede aç" class="toolbar__button toolbar__button_external"></a> </div> <div class="toolbar__tool"> <a href="https://plnkr.co/edit/uF70aXaAaPeFC80B?p=preview" target="_blank" title="korumalı alanda aç" data-plunk-id="uF70aXaAaPeFC80B" class="toolbar__button toolbar__button_edit"></a> </div> </div> <iframe class="code-result__iframe" data-trusted="1" style="height:360px" src="https://tr.js.cx/task/find-point-coordinates/source/"></iframe> </div><p>Your code should use DOM to get window coordinates of:</p> <ol> <li>Upper-left, outer corner (that’s simple).</li> <li>Bottom-right, outer corner (simple too).</li> <li>Upper-left, inner corner (a bit harder).</li> <li>Bottom-right, inner corner (there are several ways, choose one).</li> </ol> <p>The coordinates that you calculate should be the same as those returned by the mouse click.</p> <p>P.S. The code should also work if the element has another size or border, not bound to any fixed values.</p> <p><a href="https://plnkr.co/edit/uF70aXaAaPeFC80B?p=preview" target="_blank" data-plunk-id="uF70aXaAaPeFC80B">Görevler için korunaklı alan aç.</a></p></div><button class="task__solution" type="button">çözüm</button><div class="task__answer"><div class="task__step task__step_open"><button class="task__step-show" type="button" onclick="showStep(this)">Outer corners</button><div class="task__answer-content"><h4 class="task__step-title">Outer corners</h4><div class="formatted"><p>Outer corners are basically what we get from <a href="https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect">elem.getBoundingClientRect()</a>.</p> <p>Coordinates of the upper-left corner <code>answer1</code> and the bottom-right corner <code>answer2</code>:</p> <div id="u9d8lb7dce" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let coords = elem.getBoundingClientRect(); let answer1 = [coords.left, coords.top]; let answer2 = [coords.right, coords.bottom];</code></pre> </div> </div> </div></div></div></div><div class="task__step task__step_open"><button class="task__step-show" type="button" onclick="showStep(this)">Left-upper inner corner</button><div class="task__answer-content"><h4 class="task__step-title">Left-upper inner corner</h4><div class="formatted"><p>That differs from the outer corner by the border width. A reliable way to get the distance is <code>clientLeft/clientTop</code>:</p> <div id="jtb5iaitey" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let answer3 = [coords.left + field.clientLeft, coords.top + field.clientTop];</code></pre> </div> </div> </div></div></div></div><div class="task__step task__step_open"><button class="task__step-show" type="button" onclick="showStep(this)">Right-bottom inner corner</button><div class="task__answer-content"><h4 class="task__step-title">Right-bottom inner corner</h4><div class="formatted"><p>In our case we need to substract the border size from the outer coordinates.</p> <p>We could use CSS way:</p> <div id="fclkzrddh7" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let answer4 = [ coords.right - parseInt(getComputedStyle(field).borderRightWidth), coords.bottom - parseInt(getComputedStyle(field).borderBottomWidth) ];</code></pre> </div> </div> </div><p>An alternative way would be to add <code>clientWidth/clientHeight</code> to coordinates of the left-upper corner. That’s probably even better:</p> <div id="zttvekyq64" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let answer4 = [ coords.left + elem.clientLeft + elem.clientWidth, coords.top + elem.clientTop + elem.clientHeight ];</code></pre> </div> </div> </div><p><a href="https://plnkr.co/edit/pVSqYd3fJWTZi9XN?p=preview" target="_blank" data-plunk-id="pVSqYd3fJWTZi9XN">Çözümü korunaklı alanda aç.</a></p></div></div></div><button class="close-button task__answer-close" type="button" title="kapat"></button></div></div></div></div><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#show-a-note-near-the-element" name="show-a-note-near-the-element">Show a note near the element</a></h3><a class="task__open-link" href="/task/position-at" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="Görevin önemi 1'den 5'e kadar hangisidir.">önem: 5</span></div><div class="task__content"><div class="task__formatted"><p>Create a function <code>positionAt(anchor, position, elem)</code> that positions <code>elem</code>, depending on <code>position</code> either at the top (<code>"top"</code>), right (<code>"right"</code>) or bottom (<code>"bottom"</code>) of the element <code>anchor</code>.</p> <p>Call it inside the function <code>showNote(anchor, position, html)</code> that shows an element with the class <code>"note"</code> and the text <code>html</code> at the given position near the anchor.</p> <p>Show the notes like here:</p> <div class="code-result"> <div class="code-result__toolbar toolbar"><div class="toolbar__tool"> <a href="https://tr.js.cx/task/position-at/solution/" target="_blank" title="yeni pencerede aç" class="toolbar__button toolbar__button_external"></a> </div> </div> <iframe class="code-result__iframe" data-trusted="1" style="height:350px" src="https://tr.js.cx/task/position-at/solution/"></iframe> </div><p>P.S. The note should have <code>position:fixed</code> for this task.</p> <p><a href="https://plnkr.co/edit/z67ypoIB1vY8dBhi?p=preview" target="_blank" data-plunk-id="z67ypoIB1vY8dBhi">Görevler için korunaklı alan aç.</a></p></div><button class="task__solution" type="button">çözüm</button><div class="task__answer"><div class="task__answer-content"><div class="formatted"><p>In this task we only need to accurately calculate the coordinates. See the code for details.</p> <p>Please note: the elements must be in the document to read <code>offsetHeight</code> and other properties. A hidden (<code>display:none</code>) or out of the document element has no size.</p> <p><a href="https://plnkr.co/edit/QFacrobMjn6d7w4x?p=preview" target="_blank" data-plunk-id="QFacrobMjn6d7w4x">Çözümü korunaklı alanda aç.</a></p></div></div><button class="close-button task__answer-close" type="button" title="kapat"></button></div></div></div></div><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#show-a-note-near-the-element-absolute" name="show-a-note-near-the-element-absolute">Show a note near the element (absolute)</a></h3><a class="task__open-link" href="/task/position-at-absolute" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="Görevin önemi 1'den 5'e kadar hangisidir.">önem: 5</span></div><div class="task__content"><div class="task__formatted"><p>Modify the solution of the <a href="/task/position-at">previous task</a> so that the note uses <code>position:absolute</code> instead of <code>position:fixed</code>.</p> <p>That will prevent its “runaway” from the element when the page scrolls.</p> <p>Take the solution of that task as a starting point. To test the scroll, add the style <code><body style="height: 2000px"></code>.</p> </div><button class="task__solution" type="button">çözüm</button><div class="task__answer"><div class="task__answer-content"><div class="formatted"><p>The solution is actually pretty simple:</p> <ul> <li>Use <code>position:absolute</code> in CSS instead of <code>position:fixed</code> for <code>.note</code>.</li> <li>Use the function <a href="/coordinates#getCoords">getCoords()</a> from the chapter <a href="/coordinates">Coordinates</a> to get document-relative coordinates.</li> </ul> <p><a href="https://plnkr.co/edit/4SFUBkbtyzRuamYF?p=preview" target="_blank" data-plunk-id="4SFUBkbtyzRuamYF">Çözümü korunaklı alanda aç.</a></p></div></div><button class="close-button task__answer-close" type="button" title="kapat"></button></div></div></div></div><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#position-the-note-inside-absolute" name="position-the-note-inside-absolute">Position the note inside (absolute)</a></h3><a class="task__open-link" href="/task/position-inside-absolute" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="Görevin önemi 1'den 5'e kadar hangisidir.">önem: 5</span></div><div class="task__content"><div class="task__formatted"><p>Extend the previous task <a href="/task/position-at-absolute">Show a note near the element (absolute)</a>: teach the function <code>positionAt(anchor, position, elem)</code> to insert <code>elem</code> inside the <code>anchor</code>.</p> <p>New values for <code>position</code>:</p> <ul> <li><code>top-out</code>, <code>right-out</code>, <code>bottom-out</code> – work the same as before, they insert the <code>elem</code> over/right/under <code>anchor</code>.</li> <li><code>top-in</code>, <code>right-in</code>, <code>bottom-in</code> – insert <code>elem</code> inside the <code>anchor</code>: stick it to the upper/right/bottom edge.</li> </ul> <p>For instance:</p> <div id="qnhx5t8hst" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>// shows the note above blockquote positionAt(blockquote, "top-out", note); // shows the note inside blockquote, at the top positionAt(blockquote, "top-in", note);</code></pre> </div> </div> </div><p>The result:</p> <div class="code-result"> <div class="code-result__toolbar toolbar"><div class="toolbar__tool"> <a href="https://tr.js.cx/task/position-inside-absolute/solution/" target="_blank" title="yeni pencerede aç" class="toolbar__button toolbar__button_external"></a> </div> </div> <iframe class="code-result__iframe" data-trusted="1" style="height:310px" src="https://tr.js.cx/task/position-inside-absolute/solution/"></iframe> </div><p>As the source code, take the solution of the task <a href="/task/position-at-absolute">Show a note near the element (absolute)</a>.</p> </div><button class="task__solution" type="button">çözüm</button><div class="task__answer"><div class="task__answer-content"><div class="formatted"><p><a href="https://plnkr.co/edit/RnzjjRArXk6dye3P?p=preview" target="_blank" data-plunk-id="RnzjjRArXk6dye3P">Çözümü korunaklı alanda aç.</a></p></div></div><button class="close-button task__answer-close" type="button" title="kapat"></button></div></div></div></div></div></div><div class="page__nav-wrap"><a class="page__nav page__nav_prev" href="/size-and-scroll-window" data-tooltip="Window sizes and scrolling"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Önceki ders</span></a><a class="page__nav page__nav_next" href="/events" data-tooltip="Introduction to Events"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Bir sonraki ders</span></a></div><div class="article-tablet-foot tablet-only"><div class="article-tablet-foot__layout"><div class="share-icons"><span class="share-icons__title">Paylaş</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&p%5Burl%5D=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a></div><div class="article-tablet-foot__map"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Eğitim haritası</span></a></div></div></div><div class="comments formatted" id="comments"><div class="comments__header"><h2 class="comments__header-title"><a href="#comments" name="comments">Yorumlar</a></h2><div class="comments__read-before"><span class="comments__read-before-link">yorum yapmadan önce lütfen okuyun...</span><div class="comments__read-before-popup"><div class="comments__read-before-popup-i"><ul><li>Eğer geliştirme ile alakalı bir öneriniz var ise yorum yerine <a href="https://github.com/javascript-tutorial/en.javascript.info/issues/new">github konusu gönderiniz</a>.</li><li>Eğer makalede bir yeri anlamadıysanız lütfen belirtiniz.</li><li>Koda birkaç satır eklemek için <code><code></code> kullanınız, birkaç satır eklemek için ise <code><pre></code> kullanın. Eğer 10 satırdan fazla kod ekleyecekseniz <a href='https://plnkr.co/edit/?p=preview'>plnkr</a> kullanabilirsiniz)</li></ul></div></div></div></div><div id="disqus_thread"></div><script>var disqus_config = function() { if (!this.page) this.page = {}; Object.assign(this.page, {"url":"https:\/\/tr.javascript.info\/coordinates","identifier":"\/coordinates"}); };</script><script>var disqus_shortname = "tr-javascript-info";</script><script>var disqus_enabled = true;</script></div></script></main></div><div class="sidebar page__sidebar sidebar sidebar_sticky-footer"><button class="sidebar__toggle" data-sidebar-toggle></button><a class="map" href="/tutorial/map" data-action="tutorial-map" data-tooltip="Eğitim haritası"></a><div class="sidebar__inner"><div class="sidebar__content"><div class="sidebar__section"><h4 class="sidebar__section-title">Bölüm</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="/document">Document</a></li></ul></nav></div><div class="sidebar__section"><h4 class="sidebar__section-title">Ders menüsü</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#window-coordinates-getboundingclientrect">Window coordinates: getBoundingClientRect</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#elementFromPoint">elementFromPoint(x, y)</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#using-for-position-fixed">Using for position:fixed</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#document-coordinates">Document coordinates</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#getCoords">Getting document coordinates</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#summary">Summary</a></li></ul></nav></div><div class="sidebar__section"><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#tasks">Görevler (4)</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#comments">Yorumlar</a></li></ul></nav></div><div class="sidebar__section"><div class="sidebar__section-title">Paylaş</div><a class="share share_tw sidebar__share" href="https://twitter.com/share?url=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a><a class="share share_fb sidebar__share" href="https://www.facebook.com/sharer/sharer.php?s=100&p[url]=https%3A%2F%2Ftr.javascript.info%2Fcoordinates" rel="nofollow"></a></div><div class="sidebar__section"><a class="sidebar__link" href="https://github.com/javascript-tutorial/tr.javascript.info/blob/master/2-ui/1-document/11-coordinates" rel="nofollow">GitHub'da düzenle</a></div></div></div></div></div></div><div class="page-footer"><ul class="page-footer__list"><li class="page-footer__item page-footer__item_copy">© 2007—2025 Ilya Kantor</li><li class="page-footer__item page-footer__item_about"><a class="page-footer__link" href="/about">proje hakkında</a></li><li class="page-footer__item page-footer__item_contact"><a class="page-footer__link" href="/about#contact-us">iletişime geçin</a></li></ul></div></body></html>