Include jQuery into your theme through the functions.php

Posted on 21st August, 2013 Leave a Comment

Over time I’ve realized that there is a better way to include jQuery. Rather than adding your jQuery straight into the header.php or footer.php of your theme files which can be untidy, I would recommend adding a function to your function.php which is a lot neater.

So open the functions.php

scroll to the bottom and create a simple function:

	function scroll_to_top(){

};

Then create a variable to hold the script

	$script ='	';

Now add your jQuery between the single quotation marks, like this.
*Notice that if you’re using more single quotation marks you’ll need to escape them using a backwards slash or it’ll break.

$script ='<script type="text/javascript">
jQuery(document).ready(function($){
		$('a[href^="#"]').on("click",function(e) { // escape all the other single quotes
			e.preventDefault();

			var target = this.hash,
			$target = $(target);

			$("html, body").stop().animate({
				"scrollTop": $target.offset().top
			}, 900, "swing", function() {
				window.location.hash = target;
			});
		});
	});
 </script>';

finally echo the $script, so your final function will look like this.

function scroll_to_top(){

	$script ='<script type="text/javascript">
jQuery(document).ready(function($){
		$('a[href^="#"]').on("click",function(e) {
			e.preventDefault();

			var target = this.hash,
			$target = $(target);

			$("html, body").stop().animate({
				"scrollTop": $target.offset().top
			}, 900, "swing", function() {
				window.location.hash = target;
			});
		});
	});
</script>';
         echo $script;
};

Then in your footer.php add the function.

<?php scroll_to_top() ?>

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]