Change a Script to Use the jQuery Library Included in WordPress

rp_wordpress.jpegIn your WordPress travels you may want to use some script that uses some external jQuery. The problem is if you ask the script to pull from an outside source (like Google) it can conflict with the jQuery you are using in WordPress. Instead of including jQuery yourself you need to ask WordPress to include it’s copy by using the wp_enqueue_script function e.g.

wp_enqueue_script( 'jquery' );

By using that it ensures that no matter how many times the script is requested it will only be included on the page once.

You also need to modify your script so instead of using $ it uses jQuery. See the following: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

Below is a neat little script that does a show/hide. This one works but, will break other areas of your site that use jQuery.

<!-- Original Login Script that conflicts with WordPress -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>

Here is the same script where the script source has been replaced with “wp_enqueue_script( ‘jquery’ );” and all the “$” have been replaced with “jQuery”.

<!-- WordPress Version - WORKS -->
<script src="wp_enqueue_script( 'jquery' );" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".slidingDiv").hide();
jQuery(".show_hide").show();
jQuery('.show_hide').click(function(){
jQuery(".slidingDiv").slideToggle();
});
});
</script>

For added fun: here is an example of the HTML that works with the script.

<div class="slidingDiv">
<!-- Your HTML HERE -->
</div>

Lena Shore

Archives