Key Takeaways
- Pop-up windows can be used effectively and non-invasively, provided they are implemented correctly. Common faults include issues with scripting, search engines, accessibility, site management tools, pop-up killers, and options to stop pop-ups from opening.
- To create a perfect pop-up, consider using a function that can be placed in some commonly-shared JavaScript code. This function can easily be called from anywhere on the site, and it is more preferable than writing the window.open function each time. The function should handle the focus aspect, assess the state of the pop-up, close the pop-up window, and re-open it with its new dimensions.
- It is important to provide a link or button in the pop-up window itself to allow users to close it. However, if the user has scripting disabled, the ‘close this window’ link should be written to the Web page using JavaScript, and check if the window was opened as part of a window.open() method. If it is a true pop-up, the link will appear and the close() method will work; if it is not a true pop-up window, the link will not appear.
If you believe the likes of Jakob Neilsen and his supporters, nothing is more evil than pop-up windows. And in many ways, this is correct. Why? Well, we’ll list the reasons soon enough, but in a nutshell it’s because they are nearly always poorly implemented or simply not needed. This tutorial will show that, with the right thought, pop-up windows can be used without upsetting anyone – particularly the person browsing your site.
Problems With Pop-Ups
The common faults with pop-up windows are:
- If scripting is disabled, or if the browser does not support JavaScript, the pop-up will not work
- Search engines cannot follow links to pop-up windows (scripted elements are always ignored)
- Pop-ups present accessibility problems
- Site management tools (e.g. DreamWeaver) cannot update links to pop-ups if you move the destination page to another section of your site
- Many people have pop-up killers running that close the window the moment it’s opened
- In Mozilla, there is an option to stop pop-ups opening in the first place
Phew. That’s quite a list … and you could probably add your own to this list. So, how do we address these?
Scripting Disabled
With scripting disabled, the pop-up does nothing. Simple as that. But if you used a standard , there would be no such problem. So, instead of using:
<a href="#" onclick="window.open('file.htm');">
you might use:
<a href="file.htm" onclick="window.open('file.htm');return false;">
This way, if scripting is disabled, the standard link still works.
However, perhaps there is a very good reason why you want the window to open on top of the current window. If so, just add a target attribute like so:
<a href="#" onclick="window.open('file.htm');">
Bingo. Problem solved. But there’s more we can do to this!
Search Engines
With the amended code above, search engines get a standard href to follow, so that’s another issue ticked off our problems list.
Accessibility Problems
The biggest fault with pop-ups is that they take the focus away from the main browser window, and this can be disconcerting. They also present general usability issues aside from accessibility. How often have you seen someone launch a pop-up and then inadvertently click back on the launcher window and, thinking that nothing’s happened, click the link again with no result? Of course the window has opened but it’s now under the launcher window, and only moving down to the task-bar and selecting the window from there will solve this.
The trick is to inform the user that the link will open in a new window. There are a number of ways to address this:
- Include instructions as part of the link itself
- Add some instruction in a title attribute
- Use an appropriate icon to signify a pop-up is imminent
This way, if focus is lost, the user may make the connection, for example:
Open my test page (opens in a pop-up window)
Open my test page
To address the issue of losing focus on the main window, you can use JavaScript to re-set the focus. A proposed script for this appears at the end of this article.
Site Link Management Tools
If you’re in the habit of moving pages around using tools like DreamWeaver or a content management system, you would hope that links are maintained. With standard hrefs, they usually are (depending on the tool you use), but with JavaScript it’s unlikely. Returning to our code for a moment:
<a href="file.htm" onclick="window.open('file.htm');return false;">
The link above would be maintained quite nicely … almost. Half of it would — the href part. But the onclick part would probably be ignored. This is a big problem. You might think that your links have been updated, but in fact people who do have JavaScript enabled would be sent to a missing page. So, you might find your code would be changed to:
<a href="file.htm" onclick="window.open('file.htm'); <br> return false;" target="newWin">
And if you were to run a link validator on the launch page, it would appear that your link is indeed valid. So, how do we address this issue? Like so:
<a href="file.htm" onclick="window.open('file.htm'); ?<br> return false;">
There’s only one link to maintain, and the correct href will be used for the window.open method. Excellent a€“ now we’re getting somewhere!
Pop-up Killers/Mozilla Disable Pop-Ups
As with the issue of JavaScript being disabled, merely providing a standard href means that the link will still work. Now we only have to address the issue of which window has focus…
The Perfect Pop-Up Script
We recommend using a function that can be placed in some commonly-shared JavaScript code (as we’ve done with this site), and which can easily be called from anywhere in the site. This is far more preferable than laboriously writing the window.open function out each time. In addition to the URL, you might want to include parameters such as height and width, and what type of pop-up style to choose (it’s up to you what styles you define).
Here’s the code I recommend:
<a href="#" onclick="window.open('file.htm');">
The additional code in the function handles the focus aspect. If you click a link that calls this function, then click back on the page such that the pop-up is hidden, and then click on another pop-up link, the code assesses the state of the pop-up, then closes the pop-up window and re-opens it with its new dimensions.
To call the function you would use the following code:
<a href="file.htm" onclick="window.open('file.htm');return false;">
Or, to use some actual examples:
This
is my pop-up link (console mode)
This
is my pop-up (fixed mode)
This
is my (elastic mode)
Note: The ‘return false’ part effectively cancels out the default action of the href, so it won’t open the pop-up and a normal HTML windows – it will open one or the other. Try the links above with and without JavaScript enabled to see for yourself.
What more could you ask for? Well… there is one final piece of icing on this cake.
Closing the Pop-Up
Once the pop-up is opened, we might rely on people to use the browser/operating system controls to close the newly opened window.
But people don’t always do this! So we should provide a link (or button, if you prefer) in the pop-up window itself to allow users to close it. However, let’s assume that our user has scripting disabled, and that the pop-up window was opened via the standard href route. The ‘close this window’ link that you so thoughtfully provided will prompt a not very friendly dialogue like this:
To get around this problem, you should write the close link to the Web page using JavaScript, and check to see if the window was opened as part of a window.open() method. That way, if it is a true pop-up, the link will appear and the close() method will work; if it is not a true pop-up window, the link will not appear.
Here’s the code to do this:
<a href="file.htm" onclick="window.open('file.htm'); <br> return false;" target="newWin">
Try the link again, and see for yourself:
This
is my pop-up (fixed mode)
Conclusion
Hopefully this tutorial has demonstrated that pop-up links can be accessible, search-engine friendly and non-invasive. However, even if you follow all of this advice you should still ask yourself if you really need to open a new window.
One final point to note is that pop-ups should be something that people opt-in to use, so don’t use a window.onload or window.onunload event to force your pop-up window on the user. That always annoys the heck out of people… unless they wanted to buy an X10 camera or visit the ‘World’s Largest Online Casino’ but didn’t know it, that is!
The above is the detailed content of The Perfect Pop-Up. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
