Move your in page jQuery to external javascripts

This is a sample html with inline javascripts. A very common question for newbie how to move the javascript to external file, below i show you 3 method i used to apply.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>external jquery demo</title> 
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
      $(document).ready(function() {

           var buttonHandler = function() {
                $( "p" ).html( "You clicked the button" ); 
           }

           $("button").on("click", buttonHandler);

      });
  </script>
</head>

<body>
   <button> Click me </button>

   <p> Click on the button above </p>
</body>
</html>

 

Create external javascript file

Option1:

Move the entire $(document).ready into external file

$(document).ready(function() {

      var buttonHandler = function() {
          $( "p" ).html( "You clicked the button" ); 
      }

      $("button").on("click", buttonHandler);			
});

 

Option2:

If your event are based on DOM onload event, you can use this short hand for onload $(function(){  } );. 

$(function() {
   var buttonHandler = function() {
	  $( "p" ).html( "You clicked the button" ); 
   };

   /* 
      optional, you can register at html
      when DOM ready
   */
   $("button").on("click", buttonHandler);
});

 

Option3:
Move partially, so you can reuse it.

(function($){
  buttonHandler = function() {
	$( "p" ).html( "You clicked the button" );
  };	
})(jQuery);

 

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>external jquery demo</title> 
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script type="text/javascript" src="external.js"></script>
  <script>
	$(document).ready(function () {
		$("button").on("click", buttonHandler);	
	});
  </script>
</head>

<body>
   <button> Click me </button>

   <p> Click on the button above </p>
</body>
</html>
Move your in page jQuery to external javascripts

2 thoughts on “Move your in page jQuery to external javascripts

  • April 11, 2014 at 12:02 am
    Permalink

    I ɑbsolutely love your site.. Excellent colors & theme.
    Dіd you develop this amazing site yourself? Pleaѕe reρly back as I’m
    hoping to creаte myy very own blog and want to know
    where ƴou got this from or what the theme is called.
    Thanks!

    Reply
    • April 11, 2014 at 2:16 am
      Permalink

      Thank you to visit my site. I bought this themes from themesforest. You can get this from this link.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.