Search code examples
javascriptfacebook-javascript-sdkjavascript-objectsdom-events

Insert variable in "open in new window" link


I have the following code:

<script language="javascript" type="text/javascript">

var affglcid = 'xyz';
</script>

<a href="http://oursite.com/" onclick="location.href=this.href+affglcid;return false;">Link</a>

It basically takes a JS variable and appends it to a link.

So, if the variable is:

var affglcid = 'xyz';

The final link will be:

http://oursite.com/xyz

If the variable is:

var affglcid = 'zyz';

The final link will be:

http://oursite.com/zyx

It works almost perfectly. Problem is that when we open the link in an external window the URL is always

http://oursite.com/

Without the variable appended. What can we do so the scripts appends the variable even when the link is opened in a new window?


Solution

  • You have to set href on page load because when open in new window, onclick not called

    <script>
    window.onload = function setHref(){
    var aa = 'xyz';
    var oldLink=document.getElementById('link').href;
    document.getElementById('link').setAttribute('href', oldLink+aa);
    }
    </script>
    <a id="link" href="http://oursite.com/">Link</a>