Tutorial :Why can't I control the click event of this link with jQuery?



Question:

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.


Solution:1

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.


Solution:2

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.


Solution:3

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.


Solution:4

Try this:

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


Solution:5

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »