120

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!

Seabizkit
  • 2,295
  • 2
  • 13
  • 29
starbucks
  • 2,614
  • 8
  • 35
  • 52
  • 3
    Wrap the code in document.ready – karthikr Sep 03 '13 at 22:14
  • 1
    did u checked the browser's console if there are any errors, syntax or file not found or something else? – Siddharth Pandey Sep 03 '13 at 22:16
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Mar 25 '18 at 20:20

9 Answers9

193

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"

mobius
  • 4,824
  • 2
  • 24
  • 39
  • 7
    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. – starbucks Sep 03 '13 at 22:16
  • 8
    @starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :) – mobius Sep 03 '13 at 22:18
  • Adding to mental "Jquery To Learn List" - someday finally figure out what needs doc ready and what doesn't. – Shawn J. Molloy Sep 28 '14 at 17:56
  • 4
    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 Apr 22 '15 at 22:22
  • 1
    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. – Sean Kendle Apr 22 '15 at 22:24
  • 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 `` tag below your HTML, or just load the JS file in your footer. All should work. – Maximus Dec 08 '15 at 16:24
  • 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. – James Jan 13 '16 at 04:41
  • 3
    @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. – nnnnnn Jan 09 '17 at 05:55
  • 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 Jan 09 '17 at 13:54
  • 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")` – Sean Kendle Jan 09 '17 at 13:59
82

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

user5636597
  • 841
  • 6
  • 3
20

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

SaidbakR
  • 11,955
  • 16
  • 89
  • 173
  • 11
    +1 - Your answer explains why one needs the `document.ready()` function. – Kevin Feb 02 '14 at 16:51
  • 1
    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. – johnlholden May 07 '14 at 14:57
  • 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. – Andrey Shipilov Mar 01 '16 at 02:52
  • @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. – SaidbakR Sep 12 '16 at 08:56
  • 1
    @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. – Matt Aug 28 '17 at 10:53
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.?

tjons
  • 4,460
  • 5
  • 25
  • 36
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();    
    });
});
tjons
  • 4,460
  • 5
  • 25
  • 36
Black Sheep
  • 6,016
  • 7
  • 28
  • 47
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.

vicgilbcn
  • 149
  • 3
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();
    });
});
Simon Boudrias
  • 38,416
  • 12
  • 90
  • 126
Rakyesh Kadadas
  • 583
  • 6
  • 9
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

Manikandan C
  • 592
  • 7
  • 15
Abhinav Singh
  • 6,884
  • 1
  • 20
  • 31
  • 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 – Rich Steinmetz Jul 23 '18 at 10:26
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.

do-me
  • 103
  • 6