• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Navigation / Using the Target Attribute

Using the Target Attribute

Using the Target Attribute

At times you may need to launch certain links into a new window. The ‘target’ attribute is deprecated and is therefore not allowed when using XHTML with a strict doctype. Using this script, you will be able to keep your pages valid while also using the target attribute to open new windows.

Notes

  • Created by: Alan Coleman
  • Web Site: http://www.alancoleman.co.uk
  • Posted: June 11, 2007

Source Code

Paste this source code into the designated areas.

External file

Paste this code into an external JavaScript file named: targetAttribute.js

/* This script and many more are available free online at
The JavaScript Source!! http://javascriptsource.com
Created by: Alan Coleman | http://www.alancoleman.co.uk */
function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName(“a”);
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute(“href”) && anchor.getAttribute(“rel”) == “external”) {
      anchor.target = “_blank”;
    }
  }
}

// Multiple onload function created by: Simon Willison
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != ‘function’) {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  externalLinks();
});

Head

Paste this code into the HEAD section of your HTML document.

<script type=”text/javascript” src=”targetAttribute.js”></script>

Body

Paste this code into the BODY section of your HTML document.

<ul>
  <li><a href=”http://www.webdeveloper.com/” rel=”external”>Web Developer</a></li>
  <li><a href=”http://javascriptsource.com/” rel=”external”>JavaScript Source</a></li>
  <li><a href=”http://www.webreference.com/” rel=”external”>WebReference.com</a></li>
</ul>

Navigation

Related Snippets:

  • Scroll to an element smoothly (smooth scroll)
  • Ticker
  • Scroll to an element smoothly
  • Scroll to top of the page

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers