Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

570 LESSON 20: Working with Frames and Linked Windows


</p>
<script>
function popup(url) {
var mywindow = window.open(url, 'name', 'height=200,width=400');
return false;
}
</script>
</body>
</html>

When a user clicks the Launch pop-up link, a new 200×400 pixel window appears with
the contents of popup.html.
The unobtrusive approach is to skip the onclick attribute entirely and bind the popup()
function to the link in your JavaScript code. First, change the link on the page to look
like this :
<a href="popup.html" id="launchpopup">Launch popup</a>
Then you should edit the <script> tag so that it looks like this:
<script>
function popup(url) {
var mywindow = window.open(url, 'name', 'height=200,width=400');
return false;
}
window.onload = function () {
var link = document.getElementById(“launchpopup");
link.onclick = function () {
return popup(this.href);
}
}
</script>

In this case, when the page loads, I retrieve the link by its ID and then bind a new anony-
mous function to it that calls the original popup() function. Instead of hard coding the
URL, I pass this.href to the popup() function so that it opens the URL in the link.
Using a library like jQuery can make things even easier. Suppose you want any link
tag with the class popup to open a new window with the URL associated with the link.
Here’s the code:
<script>
$(document).ready(function () {
$(“a.popup").click(function (event) {
var mywindow = window.open(this.href, 'newwindow',
'height=200,width=400');
event.preventDefault();
Free download pdf