Javascript not self top

How to set the top position of an element with JavaScript?

In this tutorial, we shall learn to set the top position of an element with JavaScript. To set the top position of an element, we can use the DOM Style top property in JavaScript. Alternatively, we can use the DOM Style setProperty() method. Let us discuss our topic in brief.

Using the Style top Property

We can set or return the top position of an element using the JavaScript DOM style top property.

Following is the syntax to set the top position of an element using the Style top property with the dot notation or square brackets.

Syntax

object.style.top = "auto | length | % | initial | inherit"; object.style["top"] = "auto | length | % | initial | inherit";

With this syntax, we can set the required top position of an element to the element’s style.

Parameters

  • auto − Allows the browser to set the top position.
  • length − Sets the top position in length units. Negative values are accepted.
  • % − Sets the top position in % of the parent element’s height.
  • initial − Sets this property to its default value.
  • inherit − Inherits this property from its parent element.
Читайте также:  Copy html to clipboard yandex

The default value of the property is auto. The return value is a string representing the top position of an element.

Example 1

You can try to run the following code to set the top position of a div with JavaScript −

!DOCTYPE html> html> head> style> #myID position: absolute; > /style> /head> body> button onclick="display()">Set Top Position/button> div id="myID"> This is demo text! This is demo text! /div> script> function display() document.getElementById("myID").style.top="100px"; > /script> /body> /html>

Example 2

In this program, we are setting the top position of an element. The user selects the required top position value from the drop-down.

When the user ticks on the button, we call the function to set the element’s top position following the syntax given above.

Here, the element’s position is absolute. If the user selects inherit, the top value of the parent element is set to our element.

!DOCTYPE html> head> style> #topPosUsrParent top: 400px; > #topPosUsrEl position: absolute; background-color: #AFEEEE; > /style> /head> body> h3> Set the top position of an element using thei> top /i>property. /h3> div id="topPosUsrParent"> div id="topPosUsrEl"> Set the Top Position of this DIV br> This is Demo Text/div> /div> br> br> br> div id="topPosUsrBtnWrap"> select id="topPosUsrSel"> option selected="selected"/> auto option/> 300px option/> -1px option/> 50% option/> initial option/> inherit /select> br> p> Select a top position and click on the button. /p> button onclick="setTop();"> Apply /button> /div> br> /body> script> function setTop() var topPosUsrSelTag=document.getElementById("topPosUsrSel"); var topPosUsrSelIndx=topPosUsrSelTag.selectedIndex; var topPosUsrSelStat=topPosUsrSelTag.options[topPosUsrSelIndx].text; var topPosUsrEl=document.getElementById("topPosUsrEl"); topPosUsrEl.style.top=topPosUsrSelStat; > /script> /html>

Using the Style setProperty() Method

With this method, we can set the top position of an element by specifying the property name and value.

If the property exists in the element, this property will replace its value. Else it will create a new property and set a value.

Users can follow the syntax below for using this method.

Syntax

object.style.setProperty(propName, propValue, propPriority);

With this syntax, we can set the required property and value of an element to the element’s style.

Parameters

  • propName − The property name. Here it is top. The value can be a caseinsensitive string.
  • propValue − The property value.
  • propPriority − The priority of the property. For example, getPropertyPriority(«top») will return its priority. We can set null also. If a property is set as !important initially, and later if we need it, we can override using this priority parameter.

The setProperty() method does not return any value.

Example 3

In this program also, we are setting the top value of an absolute positioned element by getting the input from the user.

The difference in this program is that we override the top value with feature important using the setProperty method’s priority option.

html> head> style> #topPosSetAttrParent top: 300px; > #topPosSetAttrEl position: absolute; background-color: #BDB76B; top: auto !important; left: 20px; > /style> /head> body> h3>Set the top position of an element using thei> setProperty() /i>method. /h3> div id="topPosSetAttrParent"> div id="topPosSetAttrEl"> This is Demo Text br /> To set the top of this element select the position and click on the "Apply" button below./div> /div> br> br> div id="topPosSetAttrBtnWrap"> select id="topPosSetAttrSel"> option selected="selected"/>auto option/> 200px option/> -1px option/> 5% option/> initial option/> inherit /select> br> p>Select a top position to set the current top value/p> button onclick="setTopPosition();"> Apply /button> /div> br> /body> script> function setTopPosition() var topPosSetAttrSelTag=document.getElementById("topPosSetAttrSel"); var topPosSetAttrSelIndx=topPosSetAttrSelTag.selectedIndex; var topPosSetAttrSelStat=topPosSetAttrSelTag.options[topPosSetAttrSelIndx].text; var topPosSetAttrBtnWrap=document.getElementById("topPosSetAttrBtnWrap"); var topPosSetAttrEl=document.getElementById("topPosSetAttrEl"); topPosSetAttrEl.style.setProperty("top",topPosSetAttrSelStat, "important"); > /script> /html>

This tutorial reviewed the methods to set the top property in JavaScript in this tutorial.

We can easily set the top property to an absolute element with either the dot operator or square brackets.

Another method, setProperty(), helps us to either set or reset the top value. Users can choose any method based on the requirements.

Источник

Window top Property

The top property returns the topmost window in the current browser window.

The top property is read-only.

Note

The top property is not the same as the parent property.

window.top returns the topmost window in the hierarchy of windows.

window.parent returns the immediate parent of a window.

See Also:

Syntax

Return Value

Type Description
An object. The topmost window in the hierarchy of windows in the current browser window.

Browser Support

window.top is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

window.top

возвращает непосредственного родителя window , свойство window.top дает самое верхнее окно в иерархии.

Это свойство особенно полезно, когда нужно из подфрейма дойти до верхнего фреймсета.

Иногда это свойство используют, чтобы избежать показа своего сайта во фрейме.
Для этого в страницу вставляют код вида:

if (window.top !== window.window)

То есть, если текущее окно — не верхнее, то редирект верхнего окна на текущий урл.

Пляяяяяяяяяя
почему нихрена не канает, я уже все умираю.
мне надо сделать проверку
если побочное окно то сделать 1 действие
если окно главное то сделать 2 действие
т.е. имитируем нажатие клавишь мыши если нажата средняя клавиа (побочное окно открылось) сделать 1 действие
если нажата левая клавиша мыши (тоесть главное окно) то сделать 2 действие

УЖЕ ВСЕ ПЕРЕПРОБОВАЛ
window.top
window.parent
window.self
which
event
ничо не канает тупой JS

У меня такой тройной гамбургер из фреймов (делалось ещё в прошлом веке и не мной — я лишь пишу юзер скрипт, руссификатор). Каждый из них откликается на windows.top и каждый проходя проверку if(top===self) определяется как self.
Эта штука не работает как надо. Такое ощущение что ответы на windows.top идут от каждого окна в фрейме — каждый сам себя видит как топ. Скрипт в результате грузится 8 раз.

Отправить комментарий

  • Полезные.
  • Дополняющие прочитанное.
  • Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены.
    Для остальных вопросов и обсуждений есть форум.

Учебник javascript

Основные элементы языка

Сундучок с инструментами

Интерфейсы

Все об AJAX

Оптимизация

Разное

  • Асинхронное программирование
  • Google Gears в деталях
  • Javascript Flash мост
  • Букмарклеты и правила их написания
  • О подборке книг на сайте
  • Почему — плохо
  • Способы идентификации в интернете
  • Уровни DOM
  • Что почитать?
  • Шаблонизация с javascript
  • Юнит-тесты уровня браузера на связке Selenium + PHP.
  • Справочники: Javascript/HTML/CSS
  • Система сборки и зависимостей Google Closure Library
  • Хранение данных на клиенте. DOM Storage и его аналоги.
  • 10 лучших функций на JavaScript
  • BTS Jin, who went to the army, saved a.
    21 минута 32 секунды назад
  • Securely Manage Your Crypto Assets with.
    1 час 22 минуты назад
  • Ucokbet are always quick to provide.
    2 часа 13 минут назад
  • Ucokbet are always quick to provide.
    2 часа 15 минут назад
  • Ucokbet are always quick to provide.
    2 часа 17 минут назад
  • Thanks for sharing. I hope this will be.
    16 часов 8 минут назад
  • Great blog! Can you explain me more?
    19 часов 22 минуты назад
  • Xanax Kopen (Alprazolam) 2 mg online
    21 час 10 минут назад
  • a href=»https://handgun-shop.
    22 часа 23 минуты назад
  • a href=»https://handgun-shop.
    22 часа 23 минуты назад

Источник

Window self Property

The self property is often used in comparisons (see example above).

Syntax

Return Value

Browser Support

window.self is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

HTML DOM Element offsetTop

All block-level elements report offsets relative to the offset parent:

The offset parent is the nearest ancestor that has a position other than static.

If no offset parent exists, the offset is relative to the document body.

See Also:

Syntax

Return the top offset position:

Return Value

More Examples

Create a sticky navigation bar:

// Get the navbar
const navbar = document.getElementById(«navbar»);

// Get the offset position of the navbar
const sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() if (window.pageYOffset >= sticky) navbar.classList.add(«sticky»)
> else navbar.classList.remove(«sticky»);
>
>

Browser Support

element.offsetTop is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Источник

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