Why is this jQuery click function not working?

372,814

Solution 1

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

Solution 2

I found the best solution for this problem by using ON with $(document).

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

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

Solution 3

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="https://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>

Notice: In the demo replace http with https there in the code, or use this variant Demo

Solution 4

You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.

JS Code:

$(document).ready(function() {

    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();    
    });
});

Solution 5

Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?

Share:
372,814
starbucks
Author by

starbucks

Updated on January 29, 2021

Comments

  • starbucks
    starbucks over 3 years

    Code:

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();
        });
    </script>
    

    The above code doesn't work. When I click on #clicker, it doesn't alert and and it doesn't hide. I checked the console and I get no errors. I also checked to see if JQuery was loading and indeed it is. So not sure what the issue is. I also did a document ready function with an alert and that worked so not sure what I am doing wrong. Please help. Thanks!

  • starbucks
    starbucks almost 11 years
    How stupid of me!! Still learning. I thought I click function doesn't need one since it's activated on clicking vs document.ready where it loads on page load.
  • mobius
    mobius almost 11 years
    @starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :)
  • Kevin
    Kevin over 10 years
    +1 - Your answer explains why one needs the document.ready() function.
  • johnlholden
    johnlholden about 10 years
    This is a better answer because the suggestion that the jquery script must be within a 'document.ready()' function is misleading. Yes, it's safer there, but if you set up the html element for a jquery function on the fly (such as query a table row depending on what button is clicked), it needs to be outside/after that function. I mistakenly changed the name of the target div for my pop-up overlays and then spent several frustrating hours looking for a script error. Big lesson learnt.
  • Shawn J. Molloy
    Shawn J. Molloy over 9 years
    Adding to mental "Jquery To Learn List" - someday finally figure out what needs doc ready and what doesn't.
  • Sean Kendle
    Sean Kendle about 9 years
    The document ready function sets up the listeners based on what it finds on the page. If you don't do this, they are never set up. The best way to do this, however, is to delegate them with the "on()" function, instead. That way any elements added to the page after load will still work!
  • Sean Kendle
    Sean Kendle about 9 years
    Also, with the "on" function, you don't actually need to use the document ready function. It sets the listener to document level, and then scrapes the page for the elements to listen to. That's why it's a little faster to be a little more specific about what element type you want to listen to, like "div.listentome" as opposed to ".listentome". Instead of checking every element for the "listentome" class, it checks only the divs, in this example.
  • Maximus
    Maximus over 8 years
    You don't have to put it in a ready function, but the DOM does need to be loaded first. So either put it in a ready block, or put the <script></script> tag below your HTML, or just load the JS file in your footer. All should work.
  • James
    James over 8 years
    I am able to use $('body').click() outside of the $(document).ready() scope, but I am not able to use .click() for any other element unless it is within the $(document).ready() scope.
  • Andrey Shipilov
    Andrey Shipilov over 8 years
    This is a wrong answer, cause the JS code should be in the head of the DOM and not inline. The fact that you spent several hours looking for the script error is not a JS problem, it's your problem not reading the docs properly and not knowing how to use debug tools.
  • SaidbakR
    SaidbakR almost 8 years
    @AndreyShipilov Who's said that, just look at the source of this page and go down to its bottom, you will see javascript code there.
  • Flink
    Flink over 7 years
    Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)
  • nnnnnn
    nnnnnn over 7 years
    @SeanKendle - That's not how .on() works. You can (optionally) use it to create delegated handlers, but either way it doesn't "scrape the page", it binds a listener to the specific element(s) in the jQuery object you call it on.
  • Sean Kendle
    Sean Kendle over 7 years
    I wrote that comment over a year ago, but I know that now, the event bubbles up until it reaches the bound on() handler.
  • Sean Kendle
    Sean Kendle over 7 years
    It is, however, still better to be more specific in your selectors, like div.listentome, which does actually narrow down the elements to scrape when binding. And, what I was trying to elucidate with the other comment is that you should bind the listener to a parent element that's not going to be dynamically created using Javascript, because all new elements won't have listeners assigned to them if you target them directly, like $("div.dynamicListenToMe") vs $("div.parentElement").on("click", ".dynamicListenToMe")
  • Darren Shewry
    Darren Shewry about 7 years
    or, for example, z-index!
  • Matt
    Matt almost 7 years
    @AndreyShipilov - do you know how to use debug tools to troubleshoot this issue? Then please share your knowledge with others instead of offending them. Try to be constructive and fair.
  • Zeta
    Zeta almost 7 years
    Just like Flink, I also solved problem with this. Thanks.. 100 upvote..
  • mplungjan
    mplungjan about 6 years
    It is called delegation and is needed for dynamically inserted or moved content
  • Rich Steinmetz
    Rich Steinmetz almost 6 years
    so true, I am using flask/jinja and it is not working unless I use the onclick property in the HTML and refer from there to a function in my <script>