Jump to content

Get part of URL and add to specific links


Recommended Posts

Hi there,


I have the following URL:



What I would like to do is add the




part of the URL to specific links on the page based on their ID's. The ?code= and ?ref= are dynamic, so I would need to get the URL as a dynamic URL.


What would be the best way to do this?




Link to comment
Share on other sites



I don't have PHP, I only want to work with jQuery :/


I've managed to create this:


var urls = window.location.href;
$("a").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href");
   $this.attr("href", _href + urls.substring(urls.lastIndexOf('/') + 1));


This sort of works on the following code:



<a href="/sub/page.shtml"  onClick="window.open('/sub/page.shtml', ''); return false; trackOutboundLink(this, 'Outbound Links', 'my link');" >Link</a>


However, the window.open event causes the link to lose the appended URL. How can I apply the above to append the URL in the window.open?



Edited by toolman
Link to comment
Share on other sites

Here is a basic example for what you want to do, that will work for the link example you provided:

  $('a').each(function() {
    var onclick = $(this).attr('onclick')||'';
    var qs = location.search.replace('?','');
    var url=onclick.match(/window\.open\('([^']+)/);
    if (url&&url[0]) {
      newUrl = url[0] + ((url[0].indexOf('?')==-1) ? '?' : '&') + qs;
    var href = $(this).attr('href')||'';
    if (href) {
      href += ((href.indexOf('?')==-1) ? '?' : '&') + qs;

However, this is generally bad practice, as it can easily break.  The better thing to do would be to move all of the onclick code to a callback function and then attach the callback function with a click event handler.  That way, you can use a variable instead of hardcoded value and then update the variable instead of trying to scrape onclick like this. 


sidenote: your trackOutboundLink() function will never fire because of that return false; before it. 

Edited by .josh
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.