Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: intercepting out going link and adding parameters

Tags:

jquery

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

like image 702
Ian Vink Avatar asked May 14 '10 17:05

Ian Vink


2 Answers

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);
});
like image 163
Jan Willem B Avatar answered Nov 15 '22 08:11

Jan Willem B


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 use this:

$("a").click(function(e) {
    e.preventDefault();
    window.location.href = $(this).attr("href") + '?Hello=True';
});
like image 27
karim79 Avatar answered Nov 15 '22 06:11

karim79