0

I have some links on a site which I need to direct to a page telling the user that they are leaving the site. All of these links already have an onClick function on them which normall triggers an alert telling them that they are leaving the site.
For example, this would normally trigger the alert:

<a href="http://www.example.com" onclick="return displayWarning(1, this);">Example</a>

What I'm trying to do is add functionality to that displayWarning() function so that if it is passed the integer '1' as a parameter, it takes the user to the new page such as: http://www.mySite.com/warning?url=http://www.example.com

Right now I'm using this:

if(msg == 0) {   
window.location.href='/warning?url='+($(this).href);  
}

I have also tried this to see if I could just change them all at load, but seem to be experiencing the same problem:

$(document).ready(function(){   
$("a[onClick='return displayWarning(1, this);']").attr('href', '/warning?url='+$(this).attr('href'));
}); 

However, url is not being properly defined as I'm fairly certain the the context of $(this) isn't set for the way that I'm trying to call it.

I've seen similar problems mentioned below but they don't seem to solve my issue as most of them are using either the class of the links or just changing all links to some value.

How to change the href for a hyperlink using jQuery jQuery attr href, why isn't it working?

Thanks.

Community
  • 1
  • 1
jon_brockman
  • 373
  • 1
  • 11
  • Sorry, perhaps I wasn't clear on what I was trying to do. The goal was to take a user to a page on the site where they would be told that they were leaving the site. This page has an 'accept' and 'decline' button on it. So, if you click on a link to Google, you would go here: mySite.com/warning?url=http://www.google.com The accept button on that page obviously goes to google.com and the decline button would just go back a page. – jon_brockman Oct 22 '09 at 21:47
  • firstly, this sort of behaviour is not what I would deem to be a nice user experience. secondly you could hook into the window.onbeforeunload event to achieve this purpose without actually loading another web page. – barkmadley Oct 23 '09 at 14:59

3 Answers3

1

I think this is what you want:

location.href='/warning?url='+encodeURIComponent(location.href);  
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
0

I can't understand what you're trying to achieve... why doesn't you just put an if in your displayWarning function using your already this as a parameter ?

function displayWarning(parameter, anchor){
    if(parameter == 1){
        $(anchor).attr("href", "http://example.com");
    }    
}
GmonC
  • 10,924
  • 1
  • 30
  • 38
0

Thanks everyone but I ended up answering it. It turns out that there was already an object built into the function that I'm using (I didn't write it) that allowed me to grab the href value. I would, however, like to know if there is a faster way to do it.

jon_brockman
  • 373
  • 1
  • 11