0

I'm trying to use JQuery so that when the user clicks on an HTML link, a function that I write in the JavaScript file is called.

<a href="#" id="advanced_options">Show advanced options</a>

And

$(document).ready(function() {

  $("#advanced_options").click(function() {
    alert('hello');
  });

});

When I click on the link, it doesn't alert, but instead jump to another link. Why is that?

6
  • 1
    Are you loading jQuery? Check your JS console. Commented May 27, 2013 at 19:45
  • Yes, my console says I'm loading jQuery. Commented May 27, 2013 at 19:48
  • If you don't want the link to link to the top of the page, then don't say href="#". If you want a button that just does something with JS, and don't want to link to anything, then use an actual button and not a link. Commented May 27, 2013 at 19:48
  • In my console, on $(document).ready(function() it says Uncaught Type Error: Object #<HTMLDocument> has no method 'ready'. But jquery.min.js is clearly loaded. What's going on? Commented May 27, 2013 at 19:53
  • By the way, JQuery is loaded from: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> Commented May 27, 2013 at 19:54

2 Answers 2

2

If you're loading the link via an ajax query, so it's not on the page during the initial loading of the page use the jQuery on function: http://api.jquery.com/on/

$(document).ready(function() {

  $(document).on( 'click' , "#advanced_options" , function(event) {
    event.preventDefault();
    alert('hello');
  });

});
Sign up to request clarification or add additional context in comments.

Comments

1

You must prevent default browser behaviour:

$(document).ready(function() {

  $("#advanced_options").click(function(event) {
    event.preventDefault();
    alert('hello');
  });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.