Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function inside $(document).ready

Im trying to debug my web app that uses jQuery.

In firebug im calling functions inside the $(document).ready..

 function val() { console.log('validated outside doc.ready'); }  $(document).ready(function()  {      console.log('document ready...');      function validate() { console.log('validated!'); }  } 

In firebug console I type validate() and it says its not a function

If i type val() it works fine.

How do i call validate from the console ?

like image 666
IEnumerable Avatar asked Jul 10 '13 09:07

IEnumerable


People also ask

How do you call a function in document ready?

jQuery Document Ready Example ready(function() { //DOM manipulation code }); You call jQuery's $ function, passing to it the document object. The $ function returns an enhanced version of the document object. This enhanced object has a ready() function you can call, to which you pass a JavaScript function.

Can I write function inside document ready?

Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.

What does $( document .ready function () do?

$( document ). ready()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.

How can call document ready function from another function in jQuery?

$(document). ready(function() { var oneControl = $("#someControl"); // jQuery wrapper by ID var anotherControl = $("#someOtherControl"); // another wrapper // ... oneControl. click(function(event) { defineWhatToDoOnClick($(this)); // this will be the oneControl wrapper, // which you can also use }); $(window).


1 Answers

You are not calling a function like that, you just define the function.

The correct approach is to define the function outside document.ready and call it inside:

// We define the function function validate(){   console.log('validated!'); }  $(document).ready(function(){   // we call the function   validate(); }); 

Another option is to self invoke the function like that:

$(document).ready(function(){    // we define and invoke a function    (function(){      console.log('validated!');    })(); }); 
like image 164
anmarti Avatar answered Sep 23 '22 09:09

anmarti