tags:

views:

71

answers:

5

I know jQuery pretty well. This one is driving me nuts because it's SO simple.

I have this in the <head>:

<script>
$(document).ready(function() {
    $(".delete_social").click(function() {
        return false;
    });
});
</script>

and in the body I have a series of links:

<a class="delete_social" href="save_page.php?delete_social=true">Delete</a>

But EVERY time I click those links, it takes me right ot that PHP page. Why isn't jQuery intercepting the click? Any theories?

PS I've tried adding a simple alert() event to the click() function, with no change, and I've tried using "a.delete_social" in the jQuery $() call. Neither worked.

+1  A: 

Here's a couple of questions I'd ask while debugging:

  • Are you sure the click event is being attached to the anchors?
    • Try moving your script take to the bottom of the page and attaching the click events without using the ready function.
  • Is $(".delete_social").length greater than 0?
  • Are there any JavaScript errors when I load the page?
  • Is jQuery loading correctly?
    • Does $.fn.jquery return the current version of jquery you're using?
  • Consider using event.preventDefault(); instead.
Xavi
Just tried, it STILL goes to the URL. WTF??
Jason Rhodes
+2  A: 

Try this to prevent the URL from loading:

$(".delete_social").click(function(e) {
    e.preventDefault();
    return false;
});

Also, you should be getting an alert and other code to run inside the click handler. If it's not, then something else on the page is causing something weird to occur.

pygorex1
Thanks, yeah. My goal is to run an ajax $.get() in that space, to intercept the URL from the link and run it with $.get() instead. But the ajax never ran, it just went to the URL, so I stripped out the JS and tested with just return false. It's so strange.
Jason Rhodes
A: 

Try this:

<script>
$(document).ready(function() {
    $(".delete_social").click(function(event) {
        event.preventDefault();
    });
});
</script>
Neil T.
Just tried that, and it STILL goes to the URL. WTF??
Jason Rhodes
A: 

Check the rest of your javascript. return false; or .preventDefault(); should do the trick. If they're not working, it usually means there's an error somewhere else in your js, and your browser never gets to that line of code.

munch
+2  A: 

If these links are loaded in dynamically, you'll need to use $.live() to control them:

$(".delete_social").live("click", function(e){
  e.preventDefault();
  // do stuff
});

$.live() causes dynamically-added elements to adhere to previously-declared rules.

Jonathan Sampson