tags:

views:

967

answers:

2

Hi,

I want to be able to know when someone clicks a link and then reference a var within the link that I assign as a ID. For example given a link like this:

<a class="TrackClick" id="SomeUnknownVar" href="javascript:void(0)" onClick="window.open('http://someurl','','width=650,height=400,scrollbars=yes,left=150,top=100,screenX=150,screenY=100'); return false">do the deed</a>

I was hoping this little bit of JQuery would do it for me, but it doesn't

    $(document).ready(function() {
 $(".TrackClick").click(function(){ 
  trackcode = this.id;
  alert("trackcode");
 });

But that doesn't work, any ideas?

TIA!

+1  A: 

Add the url to the href, then use your jQuery added handler to open the new window. As it is, I believe the handler applied in mark up is short-circuiting the jQuery handler due to the return false. Alternatively, you could simply remove the return false and have your jQuery-applied handler stop the default action (by returning false) on the link.

<a class="TrackClick" id="SomeUnknownVar" href="http://someurl"&gt;do the deed</a>

jQuery code:

$(function() {
      $('.TrackClick').click( function() {
            var $this = $(this);
            var href = $this.attr('href');
            window.open(href,'','width=650,height=400,scrollbars=yes,left=150,top=100,screenX=150,screenY=100');
            alert( $this.attr('id') );
            return false;
      });
 });
tvanfosson
Thanks for the example code, I'll try it this way!!
Chris
This also has a slight advantage that if javascript isn't enabled, the link still works.
tvanfosson
Tvanfosson, can I ask you one more question? Is there a easy way I could apply this to both links I want to open in a new window and links that I do not? Would the best thing be to simply use another class that doesn't use the "window.open"? TIA!!
Chris
A: 

It does work here, though:

$(document).ready(function() {
    $(".TrackClick").click(function(){      
            trackcode = this.id;
            alert(trackcode);
    });
});

I only closed the missing "});" on the last line, and made the alert show the actual trackcode variable, instead of the word "trackcode".

Wow, I can't believe it was just the double quotes. This is my start into jquery so I didn't know. I think I'll try tvanfosson's solution though so there isn't any short circuiting issues. Thanks!
Chris