ThemeShaper Forums » Thematic

[closed]

Jquery in Thematic Demystified

(10 posts)
  • Started 4 years ago by helgatheviking
  • Latest reply from helgatheviking
  • This topic is not a support question

Tags:

  1. Despite its slogan "write less, do more" jquery has definitely caused me no shortage of pain in implementing any of its cool effects. After plenty of struggle I think I have come up with a process that lets me apply just about any jquery plugin w/ minimal stress.

    Here's my 3 step process:

    1. Upload your Plugin
    2. Load Libraries for Jquery and your plugin
    3. Add the jquery script that calls your plugin, aka initialize your script

    1. Upload your Plugin Script

    In my child theme I usually have a folder called "js" where I dump all the jquery plugins I am using on a particular theme. It doesn't matter what you call it, it just has to been w/ your theme and you have to know its path relative to the style.css

    2a. Load Jquery and 2b. Your Plugin Script's Library

    jquery comes with wordpress and it is enqueued by default in the admin section, but NOT on the front end. you need to tell it to load. google also hosts jquery and I usually prefer to use this. I've read that it can be faster and doesn't use your own bandwidth, but who knows for sure. you also need to enqueue the script you uploaded in step 1.

    function kia_enqueue_scripts() {
    
    	//use google's jquery
    	wp_deregister_script( 'jquery' );
    	wp_enqueue_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js');
    
    	//load up your own plugin
    	wp_enqueue_script('yourscript', get_stylesheet_directory_uri() . '/js/your-script-file.js');
    
    }
    add_action('wp_enqueue_scripts', 'kia_enqueue_scripts');

    edit: 6/19/2012. Edited because wordpress recommends enqueuing on the wp_enqueue_scripts hook and get_stylesheet_directory_uri() should replace get_bloginfo(). if you don't want to use google's jquery then just delete those 2 lines. lastly, wp_enqueue_scripts only runs on the front-end. if you need to load scripts in the backend for any reason you should use admin_enqueue_scripts() hook

    i will also often use PHP constants to make my life easier. for instance at the top of your functions.php you could:

    define('JS',get_stylesheet_directory_uri() .'/js') );

    now you can use JS across your entire theme to refer to a 'js' folder in your childtheme. get_bloginfo('stylesheet_directory'). this is just a touch neater (imho).

    using a constant, you'd then adjust your enqueue script command to look like:

    wp_enqueue_script('yourscript', JS . '/your-script-file.js');

    for more on enqueue script see the codex:
    http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    3. Add Jquery that Calls (initializes) the Plugin

    There is probably a better name for this, but it is the script that tells your site what to do. It is a common place for epic fails as jquery plugin developers often give their instructions for implementation in the jquery shorthand style of $, which doesn't work out of the box with wordpress. instead we have to play nice with WP, so I typically add my scripts in the following manner:

    function my_in_head(){ 	?>
    
    	<script type="text/javascript">
    	//<![CDATA[
    
    	jQuery.noConflict();
    	jQuery(document).ready(function($) { //tells WP to recognize the $ variable
    
    	//paste your jquery code here
    	$('body').css('backgroundColor','red');
    
    	}); //end document ready functions
    
    	/* ]]> */
    	</script>
    
    <?php }
    add_action('wp_head', 'my_in_head');

    at this point, if your body's background turns red then you have configured jquery correctly. I know it might slow the site down to put all of this jquery in the header, but personally I'd rather have it work and be a touch slower than not work at all. Worry about that later.

    Final Words on HTML Markup

    Jquery works similarly to CSS in how items are selected. All the jquery plugins that I have encountered rely on specfic HTML markup. For instance the Jquery UI "tabs" plugin works with the following markup:

    <div id="tabs">
    	<ul>
    		<li><a href="#tabs-1">Nunc tincidunt</a></li>
    		<li><a href="#tabs-2">Proin dolor</a></li>
    		<li><a href="#tabs-3">Aenean lacinia</a></li>
    	</ul>
    	<div id="tabs-1">
    		Proin elit arcu.
    
    	</div>
    	<div id="tabs-2">
    		Morbi tincidunt.
    
    	</div>
    	<div id="tabs-3">
    		Mauris eleifend est et turpis. 
    
    	</div>
    </div>

    the jquery that goes in step 3 is then:

    $( "#tabs" ).tabs();

    So if your container div is called "bacon" but you are calling the script on the #tabs selector isn't going to work. If you call the .tabs() command and you don't have the tabs.js script queued up properly, I know that firebug will give you an error message saying .tabs() isn't recognized, but I have yet to discover some sort of way to be alerted to this type of "name" error, so you just have to pay attention. if you copy and paste wholesale from the plugin's instructions, just make sure your markup matches!

    hope this helps... and please advise of any errors.

    Posted 4 years ago #
  2. This is great, thank you helgatheviking.

    Posted 4 years ago #
  3. NED
    Member

    hi helga, you mentioned you had problems with template based logic and I can't seem to get my front page to conditionally load some js scripts, thematic doesn't seem to recognize that my is_front_page_ really is my front page... do you see anything wrong with this functions code:
    HI,
    I have scoured the forums and wp to try and figure out what is going on but I cannot seem to get my functions file to recognize my static front page as such... I have followed the instructions thru wordpress > created an empty home page, gave the proper template name, built the template page and it loads fine and everything is great when viewing the home page, the problem is when I try to conditionally load some js scripts from within the functions file... here's my code but it doesn't work, any thoughts much obliged, thx ;)

    // conditionally Load js callz...
    if ( is_front_page() ) {
    function add_js_calls() {  ?>
    
    	<script type="text/javascript">
    	jQuery(document).ready(function() {
    		jQuery('#topic-scrollpane').jScrollPane();
    
    		jQuery('#slider').s3Slider({timeOut: 9000});
    
    	});
    	</script>
    
     <?php }
    add_action('wp_head','add_js_calls');
    }

    any thoughts much obliged ;)

    Posted 4 years ago #
  4. you aren't having problems with conditional you are having php order problems. your condition and function order needs to be swapped... ie.... your condition needs to be INSIDE the function like so:

    function my_in_head(){ 	?>
    
    	<script type="text/javascript">
    	//<![CDATA[
    
    	jQuery.noConflict();
    	jQuery(document).ready(function($) {
    
    <?php if(is_front_page()){ ?>
    	$('body').css('backgroundColor','red');
    <?php } ?>
    
    	}); //end document ready functions
    
    	/* ]]> */
    	</script>
    
    <?php }
    add_action('wp_head', 'my_in_head');

    this will set your front page background to red if you have jquery set up properly. once you verify this works, then replace my css change with your jquery:

    $('#topic-scrollpane').jScrollPane();
    $('#slider').s3Slider({timeOut: 9000});
    Posted 4 years ago #
  5. oakview
    Member

    Helga,

    I use it, but one issue I have with using Google's jQuery is the possibility of it being unavailable, however remote that might be. It would be a good idea to be able to fall back to the built-in Wordpress jQuery in that event, something I briefly tried to code, without much success. I needed a solution quickly for a high profile client, and ended up using some code from the jQuery Delivery Boy plugin (code below).

    I wonder if there isn't a simpler way to check if Google jQuery is loaded, then fall back to the built-in jQuery when necessary?

    // JQuery from the Google API repository
    function cdn_available( $url )
    {
    	if ( function_exists( 'curl_init' ) )
    	{
    		$ch = curl_init( $url );
    		curl_setopt($ch, CURLOPT_URL, $url);
    		curl_setopt($ch, CURLOPT_HEADER, TRUE);
    		curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
    		$data = curl_exec($ch);
    		curl_close($ch);
    
    		if (! $data) {
    			return 'Error: Exec fail';
    		}
    		else {
    			preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/", $data, $matches);
    			$code = end($matches[1]);
    			if ($code == 200) {
    				return 1;
    			}
    			elseif ($code == 404) {
    				return 'Error: 404';
    			}
    			else {
    				return "Error: Unknown ($code:$data)";
    			}
    		}
    	}
    	else {
    		return 'No cURL';
    	}
    }
    
    function jquery_delivery_boy()
    {
        $cdn = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
    	$result = cdn_available( $cdn );
    
    	if ( $result === 1 && ! is_admin() ) {
    		wp_deregister_script( 'jquery' );
    		wp_register_script( 'jquery', $cdn, NULL, '1.4.2', FALSE );
    	}
    	wp_enqueue_script( 'jquery' );
    }
    add_action('init', 'jquery_delivery_boy');
    Posted 4 years ago #
  6. very interesting oakview. so that code delivers google's version if said version is available? i read a lot of posts around the web from themers proclaiming the superiority of google's jquery for speed reasons so i went with it.

    Posted 4 years ago #
  7. oakview
    Member

    i read a lot of posts around the web from themers proclaiming the superiority of google's jquery for speed reasons so i went with it.

    I also use the Google repository, but worry that critical jQuery stuff on client sites will fail if Google's down for any reason. Yes, this code registers the Google jQuery first, and if unavailable it falls back to the local Wordpress version - I tested it. I seem to recall that this solution requires PHP 5, but not entirely sure.

    I was hoping that someone more savvy at PHP than me might see a way to accomplish this using less code. Something like this:

    if (jQuery) {
        // jQuery is loaded
    } else {
        // jQuery is not loaded, load it from elsewhere
    }
    Posted 4 years ago #
  8. I'd love to know if someone could followup on this last post. It would really be useful.

    Posted 3 years ago #
  9. Awesome, thanks Helga!

    Posted 2 years ago #
  10. welcome james. and to follow up w/ oakview's post:

    http://wp.tutsplus.com/tutorials/load-jquery-from-google-cdn-with-local-fallback-for-wordpress/

    there is quite a bit of good discussion in the comments too, which suggest that might not be a good solution after all.

    i think that html5 boilerplate is doing it with a client-side test, which is probably the best... but you have to hard-code the jquery into the header.

    Posted 2 years ago #

RSS feed for this topic

Topic Closed

This topic has been closed to new replies.