- Popups and window methods
- Popup blocking
- window.open
- Example: a minimalistic window
- Accessing popup from window
- Accessing window from popup
- Comments
- Create Pop-up Windows
- How to Use Javascript to Create Popup Windows
- Modern Pop-up Windows with Javascript
- Step 1: Add the css class to any link that you want to act as a pop-up
- Step 2: Add this javascript to the head or preferably to an external javascript file
- Pop-up Windows Examples
- Pop-up Windows
- Parent Window
- Child Window
- Opening the Pop-up Window
- Closing the Pop-up Window
- Passing Values Back to the Parent Window
- Automatically Setting and Retrieving Values
- Manually Setting and Retrieving Values
- Способы создания окон PopUp
- Введение
- Постановка задачи(ТЗ)
- Решение
- Добавление магии на Jquery
Popups and window methods
A popup window is one of the oldest methods to show additional document to user.
Basically, you just run:
…And it will open a new window with given URL. Most modern browsers are configured to open url in new tabs instead of separate windows.
Popups exist from really ancient times. The initial idea was to show another content without closing the main window. As of now, there are other ways to do that: we can load content dynamically with fetch and show it in a dynamically generated
Also, popups are tricky on mobile devices, that don’t show multiple windows simultaneously.
Still, there are tasks where popups are still used, e.g. for OAuth authorization (login with Google/Facebook/…), because:
- A popup is a separate window which has its own independent JavaScript environment. So opening a popup from a third-party, non-trusted site is safe.
- It’s very easy to open a popup.
- A popup can navigate (change URL) and send messages to the opener window.
Popup blocking
In the past, evil sites abused popups a lot. A bad page could open tons of popup windows with ads. So now most browsers try to block popups and protect the user.
Most browsers block popups if they are called outside of user-triggered event handlers like onclick .
This way users are somewhat protected from unwanted popups, but the functionality is not disabled totally.
What if the popup opens from onclick , but after setTimeout ? That’s a bit tricky.
The popup opens in Chrome, but gets blocked in Firefox.
…If we decrease the delay, the popup works in Firefox too:
The difference is that Firefox treats a timeout of 2000ms or less are acceptable, but after it – removes the “trust”, assuming that now it’s “outside of the user action”. So the first one is blocked, and the second one is not.
window.open
The syntax to open a popup is: window.open(url, name, params) :
url An URL to load into the new window. name A name of the new window. Each window has a window.name , and here we can specify which window to use for the popup. If there’s already a window with such name – the given URL opens in it, otherwise a new window is opened. params The configuration string for the new window. It contains settings, delimited by a comma. There must be no spaces in params, for instance: width=200,height=100 .
Settings for params :
- Position:
- left/top (numeric) – coordinates of the window top-left corner on the screen. There is a limitation: a new window cannot be positioned offscreen.
- width/height (numeric) – width and height of a new window. There is a limit on minimal width/height, so it’s impossible to create an invisible window.
- Window features:
- menubar (yes/no) – shows or hides the browser menu on the new window.
- toolbar (yes/no) – shows or hides the browser navigation bar (back, forward, reload etc) on the new window.
- location (yes/no) – shows or hides the URL field in the new window. FF and IE don’t allow to hide it by default.
- status (yes/no) – shows or hides the status bar. Again, most browsers force it to show.
- resizable (yes/no) – allows to disable the resize for the new window. Not recommended.
- scrollbars (yes/no) – allows to disable the scrollbars for the new window. Not recommended.
There is also a number of less supported browser-specific features, which are usually not used. Check window.open in MDN for examples.
Example: a minimalistic window
Let’s open a window with minimal set of features, just to see which of them browser allows to disable:
Here most “window features” are disabled and window is positioned offscreen. Run it and see what really happens. Most browsers “fix” odd things like zero width/height and offscreen left/top . For instance, Chrome open such a window with full width/height, so that it occupies the full screen.
Let’s add normal positioning options and reasonable width , height , left , top coordinates:
Most browsers show the example above as required.
Rules for omitted settings:
- If there is no 3rd argument in the open call, or it is empty, then the default window parameters are used.
- If there is a string of params, but some yes/no features are omitted, then the omitted features assumed to have no value. So if you specify params, make sure you explicitly set all required features to yes.
- If there is no left/top in params, then the browser tries to open a new window near the last opened window.
- If there is no width/height , then the new window will be the same size as the last opened.
Accessing popup from window
The open call returns a reference to the new window. It can be used to manipulate it’s properties, change location and even more.
In this example, we generate popup content from JavaScript:
And here we modify the contents after loading:
Please note: immediately after window.open , the new window isn’t loaded yet. That’s demonstrated by alert in line (*) . So we wait for onload to modify it. We could also use DOMContentLoaded handler for newWin.document .
Windows may freely access content of each other only if they come from the same origin (the same protocol://domain:port).
Otherwise, e.g. if the main window is from site.com , and the popup from gmail.com , that’s impossible for user safety reasons. For the details, see chapter Cross-window communication.
Accessing window from popup
A popup may access the “opener” window as well using window.opener reference. It is null for all windows except popups.
If you run the code below, it replaces the opener (current) window content with “Test”:
let newWin = window.open(«about:blank», «hello», «width=200,height=200»); newWin.document.write( «
Comments
- If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
- If you can’t understand something in the article – please elaborate.
- To insert few words of code, use the tag, for several lines – wrap them in
tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)
Create Pop-up Windows
How to Use Javascript to Create Popup Windows
If you’re in a hurry and quickly have to create a pop-up window for a single link then use the pop-up window generator.
If you can, then use the jQuery popup code instead — it’s lot more compact and sturdy. Also jQuery does a great job of reducing the cross-browser problems that often arise when using javascript.
But if you can’t use jQuery to integrate the code for pop-up window functionality into your website then use the javascript code below.
Modern Pop-up Windows with Javascript
We’ll use a more modern approach and avoid putting the javascript code into the body of your HTML document. We will keep the html and the javascript separate which is a cleaner approach and in a practical sense will make things much easier for you to maintain going forward.
I’ve configured the code for 3 different size pop-ups but you can add more or change the existing ones easily.
Step 1: Add the css class to any link that you want to act as a pop-up
You can use popup1, popup2, or popup3 for class names as in this html link code example below:
Step 2: Add this javascript to the head or preferably to an external javascript file
Click on the code to select it all and then do your CTRL+C copy magic.
Pop-up Windows Examples
If you want to see a working example of this code then check out the Pop-up Windows Examples Page.
NOTE: I’ve only tested this on modern browsers so your results may vary on Internet Explorer 8 or any of those older browsers but they should fall back gracefully and use the href destination link if a pop-up is not generated.
Pop-up Windows
Applies To: Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012
Many tasks in Enterprise Portal are performed in modal windows that are opened from list pages. The URL Web Menu Item used to open the page indicates whether the page is displayed in a modal window. This is the preferred way to use modal windows in Enterprise Portal for Microsoft Dynamics AX 2012.
In Microsoft Dynamics AX 2009, if you wanted to display information or have the user perform a task in a separate window, you had to use a pop-up window. A pop-up window is another web browser window that appears on top of the main Enterprise Portal window. Pop-up windows like this can still be used in Microsoft Dynamics AX 2012.
Parent Window
The parent window is the page in Enterprise Portal from which the pop-up window is opened. The parent window must contain a User Control that has the AxPopupParentControl component. Properties for this component allow for you to specify characteristics of the pop-up window. For example, the PopupHeight and PopupWidth properties control the size of the pop-up window.
Child Window
The child window is another page in Enterprise Portal that will be displayed in the pop-up window. It must have a URL Web Menu Item defined that points to the page. For details about how to create a web menu item, see How to: Create Web Menu Items.
The page used for the child window will typically contain a User Control that has the AxPopupChildControl component. This component is used when closing the pop-up window. It is also used when passing values from the pop-up window back to the parent window.
Opening the Pop-up Window
To open the pop-up window, use the OpenPopup method provided by the AxPopupParentControl. This method is typically called from the code for a User Control on the parent page. The OpenPopup method has one parameter, which specifies the web menu item of the page to be opened and displayed in the pop-up window.
The following example is the code for a button that was added to a User Control. The User Control contains the AxPopupParentControl component. An AxUrlMenuItem object is created that specifies the page to open in the pop-up window.
Closing the Pop-up Window
The user can close a pop-up window by clicking the close box. The pop-up window can also be closed through code for a User Control in the pop-up window. The AxPopupChildControl provides the ClosePopup method. This method requires two boolean parameters. The first specifies whether field values must be passed from the pop-up window back to the parent. The second parameter specifies whether the parent page has to post back after the pop-up window closes.
If the second parameter of the ClosePopup method is set to true, the PopupClosed event for the AxPopupParentControl will be run when the pop-up window closes. You can use the method handler for this event to retrieve values that are passed back to the parent from the pop-up window.
Passing Values Back to the Parent Window
It is often useful to pass values from the pop-up window back to the parent window. The AxPopupParentControl and AxPopupChildControl provide a collection of AxPopupField objects for this purpose. This collection is accessed through the Fields property for the component. This property provides access to the AxPopupField Collection Editor.
You will use the AxPopupField Collection Editor to create the collection of field values to pass from the child window back to the parent window. Each AxPopupField object in the collection has a Name property. It also has an optional Target property which maps the field to a control on the page. The names of the AxPopupField objects in the collection must be the same for both the AxPopupChildControl and the AxPopupParentControl. For instance, assume the AxPopupParentControl had the following set of AxPopupField objects defined:
The AxPopupChildControl must have AxPopupField objects that have the same names defined for its Fields collection. The names enable the fields to be matched as they are passed from the child back to the parent.
The values of the AxPopupField objects can be set or retrieved automatically. They can also be set or retrieved manually through code for the User Control.
Automatically Setting and Retrieving Values
If you have set the Target property for an AxPopupField object for the AxPopupChildControl, it is mapped to a field for the User Control. In the pop-up window, Enterprise Portal will automatically set the AxPopupField object value to the value that is contained in the field specified by the Target property. If you have set the Target property for the AxPopupField object for the AxPopupParentControl, the value passed back for this field from the pop-up window will automatically be retrieved and put in the mapped field.
The field specified by the Target property must be within the same naming container as the User Control, or any parent container in the hierarchy. The field must also have the Value client-side property.
Manually Setting and Retrieving Values
If you have not set the Target property for the AxPopupField objects, you can set their value manually through code in the pop-up window. Use the SetFieldValue method to do this. You can also use code in the parent window to retrieve the value of each AxPopupField object. Use the GetFieldValue method to do this.
You cannot set or retrieve an AxPopupField object value through code if you have used the Target property to map it to a field.
For example, the following is code for a button that is contained in the User Control displayed in a pop-up window. When the button is clicked, the two AxPopupField objects defined in the Fields collection have their values set. Then the pop-up window is closed.
Code for the PopupClosed event on the parent window is typically used to retrieve the values passed back from the pop-up window. The following example shows the code that retrieves the values returned by the previous example.
Способы создания окон PopUp
Введение
В данном уроке я не открою тайну для матерых верстальщиков и гуру css, но данная статья будет полезна начинающим. именно здесь вы сможете узнать, как создавать всплывающие окна поверх всего сайта.
Чаще всего такие окна появляются после совершения определенных действий на сайте, например, пользователь нажимает на ссылку «Заказать обратный звонок» и перед ним всплывает форма заказа.
Очень удобно использовать PopUp окна в связке с ajax, но это уже тема другого урока.
Всё больше и больше в сети начинает появляться веб-ресурсов, которые используют всплывающие окна PopUp. В пример можно привести всем знакомые социальные сети. Все лишние данные со скриншотов удалены.
Вконтакте
Думаю достаточно доводов, чтобы начать изучать вопрос: как же сделать на своем сайте всплывающее окно PopUp.
Постановка задачи(ТЗ)
Необходимо создать поверх всего сайта всплывающее окно с затемнением экрана.
Решение
Способ 1
Результат:
Очень часто предлагают использовать:
Да, результат получается аналогичный, но из-за того, что у нас задана высота блока «затемнения», появляются полосы прокрутки. Именно поэтому такой метод не подходит.
Способ 2
Этот способ не отличается кардинально от Способа 1, но я считаю его более удобным.
Html (без изменений)
Результат аналогичный
Благодаря свойству: min-height:100%; наш блок «затемнение» обрел ширину в 100% и минимальную высоту в 100% экрана.
Единственным минусом данного способа является то, что Internet Explorer поддерживает данное свойство только с версии 8.0.
Добавление магии на Jquery
Теперь добавим ссылки для скрытия/отображение нашего всплывающего окна.
Для этого необходимо подключить библиотеку JQuery и небольшой скрипт:
Также необходимо обновить Html:
Результат
Теперь при загрузке страницы всплывающее окно PopUp скроется.
Если мы нажмем на ссылку «Show popup», у нас появится всплывающее окно. А если нажать на ссылку «Hide popup», то всплывающее окно вновь скроется.