Intercepting a Clicked Link Url Using jQuery

Ever wanted to send a set of parameters through a link, but the only problem, is the parameters change frequently with some javascript?

taelor
3/8/2009

The Problem

Ok, so I am working on this floating, draggable, fixed position panel to help administer my blog when I log in. Yes I know, it sounds really cool. I hope to wrap it up in a Rails plugin or gem soon, or at least post all of that code on github. While I was working on this, I was getting really annoyed at my draggable panel going back to the top 0 and left 0 position every time I clicked on a new link. I wanted it to stay where ever I moved it when I goto the next page.

The Solution

I knew the solution was simple, just send in the location values of the admin panel div on every request. The implementation on the other hand was a little more complex. Luckily jQuery is the shit. All I have to do, it create a new function on a click event for every anchor tag. Right now this only works with get requests, I can deal with the put/post requests resetting the position. After I have hooked into that event, I can manipulate the href attribute and add my parameters.

The Code

The Joy

Did I say that jQuery is the shit? Makes me feel like I’m working with Ruby for the first time all over again. You know that feeling, when it feels like its just slightly coded.

Grabbing the style attributes of top and left are super easier one liners. Next I just have to grab the actual href text to manipulate. After that, you have to see what is in the url already. As of right now, I deal with 4 different cases, each one of them handled by the if else statement. This will ensure that the place you add your parameters are proper when your already sending parameters, or linking to a div. At the end you just set the anchor’s href attribute to the new url with your parameters added in.

The Collaboration

Now I think there might be some refactoring that could be done on this, so jump on github and fork this gist!

 
3/9/2009
 

Comments


B96e4f3c5b1eb95587507aaabfe9ac2f CodeJoust said...
Jan 24, 2010

What about using cookies? They presist, and are a little easier to work with. (http://plugins.jquery.com/project/cookie).

6f8b4855a89d3ebfc345913690287634 taelor said...
Feb 10, 2010

yah, I have just recently found that plugin, and I am hopefully going to start using it some. That would work really good in this situation! Thanks for the tip!

New Comment