I have a strange predicament where I can't add onclick
to anchor tags. I have to add event listeners / attach event. I want to be able to add a class to an anchor and after the document is ready - create an event listener and make it open a popup window of the links URL. So I need to collects the anchors, collect the URLs, and make it open up in a new window.
I tried creating it with a jQuery/JavaScript mix:
Custom Script jQuery/JS
$(document).ready(function() {
$numClass = document.getElementsByClassName('popUp');
$className = 'popUp';
$left = (screen.width/2)-(650/2);
$top = (screen.height/2)-(400/2);
alert($className[1]);
for(i = 0; i < $numClass; i++)
{
if($className[i].addEventListener)
{
$className[i].addEventListener('click', function(e){
getHref();
},true);
}
else{
$className[i].attachEvent('click', getHref);
}
}
function openWindow($url){
window.open(url, "location=1,status=1,scrollbars=1,width=650,height=400,left="+left+",top="+top);
}
function getHref(){
$href = className.getAttribute('href');
openWindow($href);
}
});
but it turns out length is just bring up characters. Then I found this script online:
Online Script
$(document).ready(function() {
var elArray = document.getElementsByTagName('a');
for(var i=0; i<elArray.length; i++){
if(elArray[i].className == 'popUp') continue;
for(var j=0; j<elArray.length; j++){
elArray[j].onclick = function(){
alert(this.innerHTML + ' : ' + this.href);
};
}
}
});
which is a lot shorter, but it just doesn't work, no errors just not working. Anybody have any fixes for this?
My Entire HTML Doc
<html>
<head>
<script type="text/javascript" src="jquery1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elArray = document.getElementsByTagName('a');
for(var i=0; i<elArray.length; i++){
if(elArray[i].className == 'popUp') continue;
for(var j=0; j<elArray.length; j++){
elArray[j].onclick = function(){
alert(this.innerHTML + ' : ' + this.href);
};
}
}
});
</script>
</head>
<body>
<a href="http://www.yahoo.com" class="popUp">test1</a>
<a href="http://www.google.com" class="popUp">test2</a>
<a href="http://www.msn.com" class="popUp">test3</a>
</body>
</html>