• Stars
    star
    172
  • Rank 221,201 (Top 5 %)
  • Language
    JavaScript
  • Created almost 13 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Dynamic pjax, responds to layout changes across requested pages

#djax: Dynamic pjax

##Basic usage

djax is very quick to set up, with a few markup requirements to let it work smoothly.

First include it in your header after jquery:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.djax.js"></script>

Then instantiate on the largest page element where you will have updating content. 'body' is typically the way to go with this:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('body').djax('.updatable', ['array', 'of', 'url', 'fragments', 'to', 'exclude']);
    });
</script>

Congrats, you're done! Well mostly...

##Markup

djax will track elements with the class you pass it as a first argument. In the above example I've passed the class 'updatable,' so my markup would look something like this:

<body>
    <div class="wrapper" id="main">
        <div class="updatable first" id="first">
            Here's a div that will be monitored for changes by djax.
        </div>
        <div class="updatable second" id="second">
            Here's another
        </div>
    </div>
    <div class="sidebar" id="sidebar-right">
        <ul class="updatable sidebar-list">
            <li>Everything in this sidebar...</li>
            <li>is also being tracked</li>
            <li>Some pages might not have this ul</li>
            <li>That's fine, it just won't show on them</li>
        </ul>
    </div>

Your markup can be laid out however you like, and your trackable sections can be anywhere in relation to one another. It's best to keep them top level (nesting is unnecessary and unsupported,) and there are a few requirements that allow the plugin to function properly.

###IDs

Trackable elements must all have IDs. This is how the requested page is matched up with the current page. Only trackable elements that differ between the two pages will be loaded. Trackable elements that do not exist on the requested page will be removed, and trackable elements that do not exist on the current page will be added. In order to support this, it is also necessary to ensure the parent elements of every trackable element has an ID, as well as the sibling element immediately prior to each trackable element (if one exists).

These ID's are used to add elements when necessary. If an element exists in a requested page, but not the current page, it will be inserted after the prior sibling (by ID,) or prepended to the parent element (by ID.)

##Parameters

The plugin accepts only two parameters, and only one is required.

###Tracking Class

The first and only required parameter is the class you will use to identify trackable elements. If my code looks like the below sample, every dynamic element in my markup should have a class of djaxable

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('body').djax('.djaxable');
    });
</script>

###Exceptions

By default djax works on any internal links, but sometimes you may want to exclude certain URLs on your site. The second parameter allows you to pass an array of URL fragments to exclude from djax loading. This is performed with a simple Javascript 'indexOf,' so the more of the URL you provide, the more specifically your exclusions will be matched. The below example will djax any internal links that do not contain admin, resources, or ?s= in the url.

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('body').djax('.djaxable', ['admin', 'resources', '?s=']);
    });
</script>

##DOM Replacement Callbacks (optional)

Pass in a reference to a function that will handle the DOM replacement logic. The default djax replacement uses the standard jQuery replaceWith and does an immediate replace. For transitions, fade in/outs etc, you can control when and how the new content displays on the page. The following example fades out the old content, and fades in the new content.

<script type="text/javascript">
    var transition = function($newEl) {
        var $oldEl = this;      // reference to the DOM element that is about to be replaced
        $newEl.hide();    // hide the new content before it comes in

        $oldEl.fadeOut("fast", function() {
            $oldEl.replaceWith($content);
            $newEl.show();
            $newEl.fadeIn("fast");
        });
    }
    jQuery(document).ready(function($) {
        $('body').djax('.djaxable', [], transition);
    });
</script>

##Events

###djaxLoad

By loading new content via ajax, your visitors will only encounter $('document').ready() the first time they land on your site, and any time they manually perform a hard refresh. To help address this, djax triggers a window level event on each partial load it performs. Here's an example of enabling pageview tracking with Google Analytics on a djax enabled site:

$(window).bind('djaxLoad', function(e, data) {
    _gaq.push(['_trackPageview']);
});

As a convenience, the data object passed with the event contains the requested url, the page title for the requested page, and the contents of the requested page as a string. Use something like the following code to work with the response as a jQuery object

$(window).bind('djaxLoad', function(e, data) {
    var responseObj = $('<div>'+data.response+'</div>');
    //do stuff here
});

###djaxClick

This event is triggered when a djax'ed link is clicked. Use something like the code below to scroll top before loading in new content with ajax:

$(window).bind('djaxClick', function(e, data) {
        var bodyelem = ($.browser.safari) ? bodyelem = $("body") : bodyelem = $("html,body");
        bodyelem.scrollTop(0);	
});

##Live Demo

djax arose out of a desire to use pjax with complicated and varied layouts. See here for a WordPress site using a modified version of the bones WordPress theme. djax enabling this theme took about 28 lines of code (if you count adding a class to an element as a line of code.)

There is also a small working example in the github repository. Feel free to load up any of the included html files in your browser to see how it works.

More Repositories

1

Bumper-deprecated

self hosted followup.cc/nudgemail for privacy fanatics
PHP
31
star
2

jqueryScrape

easy and light weight scraping and parsing of remote content using jQuery
JavaScript
16
star
3

wp-phinx

Proper database migrations for WordPress using Phinx
16
star
4

Bumper

Self hosted nudgemail/boomerang. Put off emails you aren't ready to deal with by scheduling them to be resent later
Ruby
13
star
5

angular-dotdotot

Angular directive for applying the dotdotdot jquery plugin- http://dotdotdot.frebsite.nl/
JavaScript
11
star
6

kleisli-run

Do notation for the monads provided by the Kleisli gem - https://github.com/txus/kleisli
Ruby
10
star
7

phuph

doc/tutorial generator for php
PHP
6
star
8

multiarmedbandit

Implements multi armed bandit algorithm
PHP
6
star
9

lens-state

Small example of using scalaz State monad and shapeless Lens to implement concise, functional logging
Scala
5
star
10

Node-WP-Monitor

Realtime monitor of Wordpress posts using db polling via Node.js and Socket.io on client
JavaScript
5
star
11

PHP-BK-Tree

BK Tree implementation in PHP
PHP
5
star
12

chicagobossboilerplate

Boilerplate for chicago boss app with signup/signin/logout + api key generation/managment
Erlang
4
star
13

wp_headjs

Uses HeadJS to load your enqueued scripts asynchronously, in parallel, executing them in order. Maintains support for script localizations
PHP
4
star
14

ZenParser

Port of http://code.google.com/p/php-zen-coding/wiki/OverviewUsage to a class for namespacing purposes
PHP
3
star
15

kleisli-validation

Validation monad build on top of kleisli gem - https://github.com/txus/kleisli
Ruby
3
star
16

kleisli-contracts

Contracts for monads provided by the Kleisli gem - https://github.com/egonSchiele/contracts.ruby https://github.com/txus/kleisli
Ruby
3
star
17

WP-Category-Sticky

WordPress plugin that allows setting sticky posts for individual category archives
JavaScript
3
star
18

composed-free-scalaz

Example of composing free algebras using scalaz
Scala
3
star
19

ruby_type_hinting

Add type safety to your ruby code, if you're into that sort of thing
Ruby
3
star
20

WP-single-use-keys

Generate single use, optionally expiring keys in WordPress
PHP
3
star
21

KanbanFlow-export

convert kanbanflow print preview to html table for easy paste into spreadsheet
JavaScript
2
star
22

jq_clicktracker_poc

jQuery clicktracker proof of concept
JavaScript
2
star
23

jqSiteTour

based off http://tympanus.net/codrops/2010/12/21/website-tour/ packaged as a jquery plugin and enable support for highlighting elements and custom next buttons
JavaScript
2
star
24

hystrix-scala

A nicer api for Hystrix in Scala
Scala
2
star
25

class.wp_options_page

Takes the pain and ugliness out of creating an options page in WP
PHP
2
star
26

dependent-types-vs-exhaustive-match

Examination of an interesting snag with an anti-climactic solution
Scala
2
star
27

mpMVC

MySQL PHP MVC framework with auto scaffolding based on models, and migrationless db
PHP
2
star
28

WP-Debug-Objects

Plugin by Bueltge, kept here for easy access
PHP
2
star
29

Tweet--for-WordPress

port of seaofclouds Tweet! Jquery plugin to WordPress plugin
PHP
2
star
30

Github-Quick-Compare

Adds ability to generate diffs between commits and non-default branches in github by shitf+clicking and ctrl+clicking on desired commits/branches
JavaScript
2
star
31

codegrader

Structured code reviews with built in performance tracking using github commits
1
star
32

sails-boilerplate

Starting point with passport local configured and passport-local policies applied
JavaScript
1
star
33

fibrecheck

Property testing via equivalence classes derived from fibrations
Python
1
star
34

beezee.github.com

My blog
CSS
1
star
35

node-googleanalytics

Google Analytics module for Node using xmldom and jquery - ported from https://github.com/ncb000gt/node-googleanalytics to be supported in latest version of node
JavaScript
1
star
36

spapp_boilerplate

Boilerplate for heroku ready single page apps using sinatra
JavaScript
1
star
37

scrum-poker

dead simple scrum poker variation on https://github.com/ericraio/socket.io-chat-demo
JavaScript
1
star
38

burndown-charts

Web app for creating and managing burndown charts
JavaScript
1
star
39

fp-crash-course-js

Just some monads in javascript
JavaScript
1
star
40

WP-Custom-Taglines

PHP
1
star
41

proof

Using agda for book exercises
Agda
1
star
42

scalaz-writer-validation-example

Example of using writer with validation
Scala
1
star
43

mp_clone

playing with highcharts and ruby
JavaScript
1
star
44

backbone-skeleton

Skeleton Boilerplate with Backbone JS ready to go
JavaScript
1
star
45

caketodo

Simple todo app in cake PHP
PHP
1
star
46

jqModuleLoader

jQuery plugin and coding standard that allows chained dynamic loading of js and namespacing of loaded code by script
JavaScript
1
star
47

ex_compose_streams

Elixir module to work with multiple streams as if they were one stream
Elixir
1
star
48

dogears_hosted

service for syncing dogears to web
JavaScript
1
star
49

Bigdog

Rails Tutorial
Ruby
1
star
50

Less-Compiler-Loop

Node app to loop through various configs and compile one stylesheet based on each
JavaScript
1
star
51

Node-Worker-Manager

Provides convenience API and worker management to node webworkers module by @pgriess
JavaScript
1
star
52

playlistr

YouTube IV
JavaScript
1
star
53

hmapis

excercises from hypermedia apis book
JavaScript
1
star
54

GAE-Django-base-app

as provided by allbuttonspressed
Python
1
star
55

mabanditdemo

Short demo of multiarmedbandit use
PHP
1
star
56

fp-js

Functional programming exercises in javascript
JavaScript
1
star
57

kleisli-conversions

Conversions and lift methods for monads provided by the Kleisli gem - https://github.com/txus/kleisli
Ruby
1
star
58

rails-tutorial

Ruby
1
star
59

tweetconnossieur

Intelligent twitter bot that indexes followed users by their tweet content, and makes introductions among them accordingly
1
star
60

GAE-Django-site

brianzeligson.appspot.com
Python
1
star
61

WP_Query_tree

Shows a tree structure of calls that initiated all db queries executed on a page when ?querytree param is added to url by logged in admin
1
star
62

try_git

1
star
63

shapeless-validation-examples

Using generics to prove a case class can be validated, and executing validation
Scala
1
star
64

pomotodoro

Pomodoro + Todo
JavaScript
1
star
65

jQueryScrapeDemo

Demo for jQueryScrape plugin
JavaScript
1
star
66

pods-geocomplete-field

Adds GeoComplete as a field option in WP Pods framework (http://ubilabs.github.io/geocomplete/)
PHP
1
star
67

chrome-dogears

Chrome extension to manage small set of easily overwritable/updatable bookmarks
JavaScript
1
star