Categories:

So what's the point?

Like many more complex techniques, the usefulness of custom collections may not leap out at you instantly. Essentially, custom collections enable your script to easily reach out to more than just one element on the page.

In a XML document, even the "target" attribute isn't allowed inside <a> tags. The below script uses the ID attribute and custom collection technique we just learned to get select links on our page to open in a new window programmatically:

Demo:

JavaScript Kit
CSS Drive (New window)
Coding Forums (New window)

Source:

<a href="http://www.javascriptkit.com">JavaScript Kit</a><br />
<a id="new0" href="http://www.cssdrive.com">CSS Drive</a> (New window)<br />
<a id="new1" href="http://www.codingforums.com">Coding Forums</a> (New window)<br />

<script type="text/javascript">

function customcollect(idbase){
var customarray=new Array()
if (document.getElementById){
var i=0
while (document.getElementById(idbase+i)!=null){
customarray[i]=document.getElementById(idbase+i)
i++
}
return customarray
}
}

var newwinlinks=customcollect("new")
for (i=0; i<newwinlinks.length; i++)
newwinlinks[i].onclick=function(){
window.open(this.getAttribute("href"))
return false
}

</script>

To get any link on the page to open in a new open, all you have to do is give it an ID attribute, suffixed sequentially starting with "0."