Javascript – How to call function inside jQuery code

Review a Javascript code snippet to call a function which declared inside jQuery code :


<script>
   //javascript
  function submitSearchForm() {

	updateErrorMessage("Please enter a website url");
		
  }

  //jquery
  jQuery(document).ready(function($) {

	function updateErrorMessage(msg) {
		$('#error').html(msg).hide().fadeIn(500);
	}

     }
  );
</script>

But, browser console shows the updateErrorMessage function is not defined.


   Uncaught ReferenceError: updateErrorMessage is not defined

Solution

To call the function which is declared inside jQuery code, make it global access by adding the function to window object :


<script>
  function submitSearchForm() {

	updateErrorMessage("Please enter a website url");
		
  }

  jQuery(document).ready(function($) {

	//make it global access
	window.updateErrorMessage = function(msg) {
		$('#error').html(msg).hide().fadeIn(500);
	}

     }
  );
</script>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
DracoPedroJeerapong PutthanbutEmma Recent comment authors
newest oldest most voted
Draco
Guest
Draco

what if the javascript is in another file and not in the same file in which jquery code is written

Pedro
Guest
Pedro

good mate you save my day =)

Jeerapong Putthanbut
Guest
Jeerapong Putthanbut

Thankz to give the great article.
Have found many people mention this kind of issue a lot
in the https://forum.jquery.com/topic/jquery-accessing-functions-inside-document-ready

Emma
Guest
Emma

But you would want the function to have something like this

function myFunction ()
{
$(‘.selection’).css({display:none});
}