| JavaScript Popup Window that Works When JavaScript Is Disabled |
|
|
|
| Thursday, 13 April 2006 | |
|
Whether you love 'em or hate 'em, they're here to stay. Many sites use JavaScript popup windows to present additional information to users. Why not make them more usable? To overcome the fact that some users have JavaScript disabled, popup windows should still open when users need them. What we need is this: if JavaScript is enabled, the link opens a popup window, but if JavaScript is disabled, loads the page in the main browser window. The ProblemNormally, a JavaScript popup window is all or nothing, as seen in this code. The link executes a JavaScript statement that launches a popup window to load an HTML page. But if JavaScript is disabled, the JavaScript interpreter will not run the code. The link will do nothing and the user will have no way to access the content. <script type="text/javascript"> function Popup(sURL) { var w = window.open(sURL,'','width=500,height=600') } </script> <a href="javascript:Popup('/examples/css/centering_css_layout/')">Open popup</a> The SolutionThe basic plan is to provide a backup plan: if JavaScript is disabled, then the HTML page should load in the main browser window. To accomplish our plan we need a way to include a normal HTML link. We might try to move the JavaScript to an onclick event handler and use the href for the http link. Good Try But Won't Work<script type="text/javascript"> function Popup(sURL) { var w = window.open(sURL,'','width=500,height=600') } </script> <a href="/examples/css/centering_css_layout/" onclick="javascript:Popup(this.href)">Open popup</a> Note that I passed the URL using this.href, which keeps me from having to repeat the same URL information in two places. I will keep that little trick in the final solution, but there is still a problem with this code that needs to be fixed. The problem with the code above is that if JavaScript IS enabled, the content will load in both a popup window AND the main browser window. When the user clicks the link, the href will load the content into main browser window; and the onclick event handler will execute the JavaScript which will open a popup window that also loads the same content. The Real SolutionAll we need to do is slightly modify the previous code, by adding return false to the end of the JavaScript code in the onclick event handler. If JavaScript returns a value of false, the browser knows to not follow the href link. Simple, eh? Here is the code with return false added. <script type="text/javascript"> function Popup(sURL) { var w = window.open(sURL,'','width=500,height=600') } </script> <a href="/examples/css/centering_css_layout/" onclick="javascript:Popup(this.href);return false;">Open popup</a> ConclusionAnd that's it! The two tricks that solved are problem are:
|
|
| Last Updated ( Friday, 14 April 2006 ) |
| < Prev | Next > |
|---|










