tags:

views:

39

answers:

4

When a user clicks a link on my page, I need to, before it gets actioned by the browser, add the param Hello=True to the url.

So, the user clicks MyPage.aspx in and gets sent to MyPage.ASPX?Hello=True instead.

Has to be client side, preferably using jQuery

I can add an attribute to the tags if needed.

Ian

+4  A: 

You can change all the links on your page like so:

$("a").each(function() {
    $(this).attr("href", $(this).attr("href") + '?Hello=True'));
}

If you want to redirect the user with those added parameters upon clicking a hyperlink:

$("a").click(function(e) {
    e.preventDefault();
    window.location.href = $(this).attr("href") + '?Hello=True';
}
karim79
But he wants to change URL without redirecting.
sundowatch
@sundowatch - the second example does exactly what he asked, "before it gets actioned by the browser, add the param Hello=True to the url". He means *before* the *current* href of the clicked link is followed, add parameters to it and redirect including the parameters.
karim79
A: 

You can't change URL with JavaScript without redirecting.

You can use window.location=url;

And also you may want to look this site : http://ajaxpatterns.org/Unique_URLs

sundowatch
+3  A: 

if you need all links to be manipulated, use this:

$('a').each(function() {
  var href = this.href;
  if (href.indexOf('?') != -1) {
    href = href + '&Hello=True';
  }
  else {
    href = href + '?Hello=True';
  }
  $(this).attr('href', href);
});
Jan Willem B
This is exactly what I am doing on our sites. Works like a charm. Of course, the link is changed BEFORE click...so that may not be what OP is looking for.
Bradley Mountford
cleaner/shorter/better version:$('a').each(function(){ var sep = (href.indexOf('?') != -1) ? ' $(this).attr('href', href + sep + 'Hello=True');});
arnorhs
+1  A: 

A cleaner/shorter/better version of @Jan Willem B's version:

$('a').each(function(){ 
    var sep = (this.href.indexOf('?') != -1) ? '&' : '?'; 
    $(this).attr('href', href + sep + 'Hello=True'); 
});

You could also place the statement in a single line, sacrificing readability:

$('a').each(function(){ 
    $(this).attr('href', href + ((this.href.indexOf('?')!=-1)?'&':'?') + 'Hello=True'); 
});

That's that

arnorhs
Thank you, this is excellent
BahaiResearch.com