SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Open a New Window

    when a user click on a link, it would open a new window in HTML it is something like this:
    Code:
    <a href="http://google.com" target="_blank">click here</a>

    How do I do this in Javascript? So a user would click on the link and it would open a new window. Here's my code
    Code:
    document.writeln('<tr><td>' + "http://google.com" + '</td></tr>');
    I know window.open(url) would open a new window, but how do I make it clickable??

    Any comments or suggestion would be greatly appreciated.
    thanks

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You need the onclick event:

    Code javascript:
    var theLink = document.getElementById('container').getElementsByTagName('a')[0];
    theLink.onclick = function() {
      window.open('http://sitepoint.com');
    }

    The assumption there is that the link is the first or only one in a container with the ID "container". But it of course depends on your HTML structure.

    Be careful with new windows. Popup blockers are very common and you risk annoying your users when they click something and nothing appears to happen. You should either avoid new windows or warn your users that the link will open a new window.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    how do I put your code in here??

    document.writeln('<tr><td></td></tr>');

  4. #4
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You don't. You just put it at the end of the body:

    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <div id="container">
      <p>Here is a <a href="http://google.com">link</a></p>
    </div>
    <script>
    var theLink = document.getElementById('container').getElementsByTagName('a')[0];
    theLink.onclick = function() {
      window.open(this.href);
      return false;
    }
    </script>
    </body>
    </html>
    Note that I changed the JS a bit.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •