Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Jquery function is not working

Tags:

jquery

This simple function isn't working. Showing following error

'myfunc' is undefined

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    function myfunc(){
      alert('In');
    }
  })
</script>
<button type="button" onclick="myfunc()">Alert</button>
like image 777
Talent Runners Avatar asked Dec 24 '22 21:12

Talent Runners


1 Answers

It's a scope issue, myfunc isn't in the global scope. When you put it inside $(document).ready() you would only be able to call it inside the document.ready() callback.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  //this doesn't need to be in document.ready(), it won't get called until button is already loaded anyway
  function myfunc() {
    alert('In');
  }
</script>
<button type="button" onclick="myfunc()">Alert</button>

You can read more about how scoping works in JS at http://www.w3schools.com/js/js_scope.asp

like image 117
Keatinge Avatar answered Mar 25 '23 05:03

Keatinge