Calling a user defined function in jQuery

user269867 picture user269867 · Mar 26, 2010 · Viewed 372.8k times · Source

I am trying to call a user defined function in jQuery:

I tried the following as well:

$(document).ready(function() {
  $('#btnSun').click(function() {
    myFunction();
  });
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

It doesn't seem to work! Any idea where I am wrong?

Answer

Nick Craver picture Nick Craver · Mar 26, 2010

If you want to call a normal function via a jQuery event, you can do it like this:

$(document).ready(function() {
  $('#btnSun').click(myFunction);
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>