Why is this jQuery click function not working?
Asked Answered
D

9

133

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!

Dissever answered 3/9, 2013 at 22:12 Comment(3)
Wrap the code in document.readyKenishakenison
did u checked the browser's console if there are any errors, syntax or file not found or something else?Flatfish
Possible duplicate of Why does jQuery or a DOM method such as getElementById not find the element?Loricate
B
219

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"

Bever answered 3/9, 2013 at 22:14 Comment(10)
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.Dissever
@Dissever Don't worry about it too much, everyone makes mistakes, and especially when learning :)Bever
Adding to mental "Jquery To Learn List" - someday finally figure out what needs doc ready and what doesn't.Thibaud
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!Casiecasilda
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.Casiecasilda
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.Threat
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.Feaster
@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.Rabbet
I wrote that comment over a year ago, but I know that now, the event bubbles up until it reaches the bound on() handler.Casiecasilda
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")Casiecasilda
D
99

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

Disadvantageous answered 3/12, 2015 at 19:22 Comment(3)
Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)Epiphyte
Just like Flink, I also solved problem with this. Thanks.. 100 upvote..Backhouse
It is called delegation and is needed for dynamically inserted or moved contentPryor
C
24

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

Cords answered 3/9, 2013 at 22:25 Comment(5)
+1 - Your answer explains why one needs the document.ready() function.Lode
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.Kreegar
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.Technical
@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.Cords
@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.Assiut
I
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.?

Iphigeniah answered 3/9, 2013 at 22:14 Comment(0)
B
5

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();    
    });
});
Bullring answered 3/9, 2013 at 22:18 Comment(0)
V
3

Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.

Verduzco answered 3/10, 2014 at 10:23 Comment(1)
or, for example, z-index!Dauntless
M
3

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});
Mckinleymckinney answered 8/3, 2017 at 11:4 Comment(0)
D
2

Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target

Deferral answered 4/10, 2016 at 10:10 Comment(1)
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>Surgery
L
0

Proper Browser Reload

Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.

See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.

Lymphosarcoma answered 28/1, 2021 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.