Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a user defined function in jQuery

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

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

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?

like image 966
user269867 Avatar asked Mar 25 '10 23:03

user269867


People also ask

How can I call function in jQuery?

You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. If you want an event to work on your page, you should call it inside the $(document).

Can we use function in jQuery?

In jQuery we can assign function in custom namespace. We can add or remove the function from namespace. This mechanism provide the functionality of storing the related function in a namespace.

How do I call a jQuery function from another page?

JavaScript runs in the browser and so no you won't be able to call it remotely. You will need to have access to the same script on your "other page" and add the loadAccountInformation function as a click handler to the link in the same way you do on the accounts page.


2 Answers

Just try this. It always works.

$(document).ready(function() {    $('#btnSun').click(function() {      $.fn.myFunction();    });    $.fn.myFunction = function() {      alert('hi');    }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <button id="btnSun">Say hello!</button>
like image 31
neeraj Avatar answered Sep 28 '22 01:09

neeraj


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>
like image 78
Nick Craver Avatar answered Sep 28 '22 01:09

Nick Craver