amartin94
amartin94

Reputation: 515

How to pass href variables to javascript

So ive got a JS function that's run when multiple html href's are clicked. That is to say, i have about 4 different href's that look similar to this:

<a href='#' onClick="myPopup()">New Window</a>

and my JS looks like this :

<script language="javascript" type="text/javascript"> 
<!--
function myPopup() 
{
    window.open( "account_edit.php", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" )   
}
//-->
</script>

my point is, i dont want to have to re-write that one block of script another 3 times. Is there a way i can get the script to tell which href was clicked, then open up its respective page? Obviously normal href's are out of the picture, else i would do it. Thanks for the help!

Upvotes: 0

Views: 187

Answers (3)

Nicolas Straub
Nicolas Straub

Reputation: 3411

function myPopup(target) 
{
    window.open( target, "myWindow", "status = 1, height = 300, width = 300, resizable = 0" )   

then call it from each <a> with a different target:

<a href='#' onClick="myPopup('account_edit.php')">New Window</a>

Bonus Track: you can make this unobtrusive with jquery (much cleaner!)

HTML:

<a href="account_edit.php">New Window</a>

JS:

$(function(){
    $('a').click(function(e){
        e.preventDefault(); //prevents browser from following link
        window.open( this.href, "myWindow", "status = 1, height = 300, width = 300, resizable = 0" )
    });
});

note: if you don't specify a fqdn, the browser will prepend your current URL path to the href (so if you call this from abc.com/test/test.htm the popup will open in abc.com/test/account_edit.php)

Upvotes: 4

Yatin Trivedi
Yatin Trivedi

Reputation: 669

just pass some arguments within your javascript function call like New Window, New Window and so on

Upvotes: 1

samayo
samayo

Reputation: 16495

Well, you could pass something unique through the parameter:

<a href='#' onClick="myPopup('link1')">New Window</a>

then here:

<script language="javascript" type="text/javascript"> 
function myPopup(link) 
{
    alert('you cliked on link '+link); //or do whatever your want
}

</script>

Upvotes: 1

Related Questions