Code:
1 <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
2 <script type="text/javascript">
3 $("#clicker").click(function () {
4 alert("Hello!");
5 $(".hide_div").hide();
6 });
7 </script>
8
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!
Answer
You are supposed to add the javascript code in a $(document).ready(function() {}); block.
i.e.
1 $(document).ready(function() {
2 $("#clicker").click(function () {
3 alert("Hello!");
4 $(".hide_div").hide();
5 });
6});
7
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”
ads