0

I'm very new to jQuery, but from what I've read, this doesn't make sense to me. Here is my code:

$(function() {
    function grid() {
        $("#main").hide();
    }
});

<html>

  <head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="numbers.js"></script>
  </head>

  <body>
    <div id="main" style="height:90vh; width: 90vw; background-color:lightgray">
      <button onclick="grid()">grid</button>
    </div>
  </body>

</html>

When I put$(function(){...}); around my code, it never runs and the console returns ReferenceError: grid is not defined, but if I remove $(function(){...}); then everything runs fine.

karel
  • 5,489
  • 46
  • 45
  • 50
Raza
  • 41
  • 5
  • 1
    Just remove it. `grid()` needs to be in global window scope in order to be accessed by `onclick`. If you have other jQuery inside it....move grid() outside – charlietfl Feb 03 '19 at 18:55
  • 1
    That's one of the reasons why you should not use inline event handlers (`onclick="grid()"`) but use `$('selector').on('click', grid)` at the place where `grid` is visible to attach the event listener. – t.niese Feb 03 '19 at 18:56
  • 1
    [What does $(function() {} ); do?](https://stackoverflow.com/questions/7642442/what-does-function-do): The code inside of it is executed when the DOM is ready. – t.niese Feb 03 '19 at 18:59

2 Answers2

3

The code within $(function() { }) has its own scope, so when you define a function within that, that function only exists within that scope. However, you have:

<button onclick="grid()">grid</button>

Which looks for a function called "grid" in the global scope (where it doesn't exist).

Ideally, if you are using jQuery, you would do something more like:

<button id="grid">grid</button>

$(function(){
    $('#grid').on('click', function() {
        $("#main").hide();
    });
});
dave
  • 62,300
  • 5
  • 72
  • 93
0

you can call a javascript function or define onClick listener of button inside $(document).ready

// using jquery 
$(document).ready(function() {
    $('#grid').click(function(){
        $("#main").hide();
    });
});

// using javascript function
function grid(){
   document.getElementById('main').style.display = 'none';
}
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="numbers.js"></script>
  </head>
  <body>
    <div id="main" style="height:90vh; width: 90vw; background-color:lightgray">
      <button id="grid">grid</button>
       <button onclick="grid()">grid2</button>
    </div>
  </body>
</html>
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71