Share Tweet Reccomend

Backbone.js Routers

In what follows, we are going to look at Backbone.js routers. Routers are a great place to start whenever you begin developing a Backbone application (or any application for that matter) because you can figure out what URLs and sections your app will need and add hooks in your code to respond to them. It helps define application structure, much like a flow chart would.

The files for demo and download for the following discussion can be found below if you’d like to follow along…

View Demo Download Files

Backbone.js uses routers to execute certain actions when a user goes to a certain URL within a Backbone application. Backbone applications all use routes that follow a # character in the URL. The # might be familiar to you if you’ve ever used it as a named anchor to link to part of the current document without going to a new URL. This is very prevalent in pages that have tables of content at the top (e.g. like in Wikipedia articles), where the links at the top take you to a place on the same page further down. That’s what’s going to happen with Backbone. We’re going to stay on our same page, but we’re going to set up our JavaScript such that Backbone listens for the user going to these links. When the user clicks on different links within the application, instead of going to a different place on the page, we’ll be executing different portions of JavaScript in our code. That’s how a “client-side JavaScript application” essentially behaves.

Read More »

Share Tweet Reccomend

jQuery: What’s the Difference Between $(this), $this, and this?

When doing jQuery development and looking at the code in other people’s jQuery functions and plugins you’ll eventually see that different developers will use different syntaxes in different places. This is probably most apparent in the use of the term “this”. Sometimes you will see this. Other times you will see $(this) and still other times you will see $this. What is the difference between all of these and when should you use each one?

The this pointer in JavaScript refers to the current object that we are running our code inside. In JavaScript everything is an object, so the scope of this is always changing.

Let’s say we had a page like one that is shown below…

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<div id="one" class="myClass">One</div>
<div id="two" class="myClass">Two</div>
<div id="three" class="myClass">Three</div>
<div id="four" class="otherClass">Four</div>
<script type="text/javascript">
</script>
</body>
</html> 

Now in the <script> section let’s add some jQuery to loop through all of the elements with the “myClass” class (all the <div>’s on the page. As many know, to do this we use the jQuery each method. Inside of each we can use the pointer “this” to refer to the current DOM element in set of elements we are on.

$(document).ready(function() {
    $('.myClass').each(function(){
       // do something with this here
    });
});

Let’s use the native JavaScript function getAttribute() to get the id attribute of each element.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.getAttribute('id'));
    });
});

If we look in our console, we can see that the text one, two, three appears (the id attributes of each DOM element that has “myClass”). So everything works as expected.

But as you know jQuery also has a method for getting an attribute: the attr() method. So let’s try it with that.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.attr('id'));
    });
});

However if we look in our console we get an error.

Uncaught TypeError: Object # has no method ‘attr’.

Why is that? We know we are referencing the correct DOM element. Well, it’s because we haven’t wrapped this (the current DOM element) in jQuery so that we can call jQuery methods on it. That’s really the big distinction between $(this) and this. They both refer to the same object. However, if you want to use any jQuery on the object, it must be wrapped in a jQuery object as $(this) like so.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log($(this).attr('id'));
    });
});

The reverse is also true. Because the $() is a jQuery wrapper, you cannot call native JavaScript on it. So $(this).getArribute(‘id’) also wouldn’t work.

So that’s the big thing to remember. If you want to call a jQuery method on your object, wrap it it $(). If you want to use a native JavaScript method, don’t wrap it in $(). Just use plain ol’ this

What about $this?

$this is a little different because it’s actually just a variable that uses the $. It has no inherent relation to jQuery. It would be no different than JavaScript variables named $corn or $carrots. You just was easily say var $this = “My pet cat is named Mittens.”; It’s just a variable with the dollar sign in it. JavaScript allows characters like this in variable names. The reason that you see use of $this inside of jQuery plugins is that often times developers in the global scope inside of their plugin will say something like:

var $this = $(this);

That way they can always have a reference to the object on which the plugin was called. The scope of “this” will change in any methods used inside the plugin so it’s always good to have a global variable (that is, global inside the plugin scope) which you can refer to the object on which the plugin was called. But the important thing to remember is that $this has no inherent relation to jQuery. It’s just a variable like any other.

Personally however, I never really liked naming the DOM element object using that convention. I always used var object = $(this); as can be seen in some jQuery plugins I have written. I figured with all the this’s running around inside of all of these objects, no need to throw another one in there if not absolutely necessary. But it’s really just a matter of personal preference there :)

Hopefully this has cleared up some of the weirdness in uses of different this syntaxes.

Share Tweet Reccomend

Create a Responsive jQuery Accordion

In this post I am going to show you how to create an accordion that will slide down on click using CSS and jQuery. There are a lot of tutorials out there that will show you how to do something similar to this but what I like about this accordion is that it uses <div>’s of content rather than list items for each of the accordion sections. A lot of tutorials show how to make menu-style accordions but not necessarily ones for any content that you want. That’s what this aims to accomplish.

Before we start, I think I should mention that this accordion is not technically “responsive” in the sense that it has any media queries attached to it, only that the percentage-width based fluidity of it should allow you to fit it into any content area as the viewport resizes.

View Demo

It’s also going to be “vanilla” enough such that it’s not overstyled to the point where you’re going to have to undo a lot of the styling to fit the theme of your website (should you want to integrate it). It’s going to be fairly bland, boilerplate, and basic, but that’s always a good place to build from.

The width of the accordion is going to be percentage based so that it should adapt well for responsive designs as well.

So start and we’re going to lay out our basic structure in the HTML….

<div class="accordion">
  <div class="accordionHeader"><span>One</span></div>
  <div class="accordionContent">Mauris quis tellus sed mi bibendum vulputate. Nam nec fermentum leo. Donec ante nisl, varius nec scelerisque nec, pulvinar id ipsum. Phasellus sodales tellus quis odio tincidunt quis feugiat sapien mollis. Ut hendrerit nisl eu turpis mattis sit amet accumsan ante pretium. 
  </div> 
  <div class="accordionHeader"><span>Two</span></div>
  <div class="accordionContent">Vestibulum neque justo, rutrum eu interdum sed, aliquam sit amet nulla. Pellentesque ultricies enim sit amet urna fringilla venenatis. Etiam eleifend dolor ut felis sagittis quis dignissim neque venenatis. In posuere tempus sodales. Aliquam tellus ante, posuere vitae congue at, tempus sed dolor. Etiam ac urna leo, at pellentesque augue osuere vitae congue at. Imperdiet ac euismod leo viverra. Maecenas convallis, lectus sit amet eleifend vehicula, sapien sem pretium dolor, in tincidunt est sapien eget orci. Sed vel libero urna. Aliquam ornare sodales egestas. Duis feugiat vulputate libero id tempor. Pellentesque elementum molestie nisi ac elementum
  </div> 
  <div class="accordionHeader"><span>Three</span></div>
<div class="accordionContent">Nunc elit nisl, vestibulum ac laoreet nec, cursus sed leo. Aenean sit amet nibh justo. Quisque dui arcu, pharetra non sollicitudin nec, rhoncus at ligula. Etiam placerat porttitor adipiscing. Aenean fermentum nulla a justo malesuada id pulvinar urna sagittis. Morbi urna orci, faucibus sed sollicitudin sit amet, faucibus dictum massa. In sit amet enim at nisi rutrum vulputate. Vestibulum quis mattis nulla. Duis viverra orci ut enim tincidunt auctor. Ut molestie eros eget mauris consectetur eget tristique arcu elementum. </div> 
  <div class="accordionHeader"><span>Four</span></div>
  <div class="accordionContent">Nulla sollicitudin laoreet nulla quis suscipit. Curabitur tristique, dolor vel condimentum molestie, purus leo sodales enim, ac vehicula sem est eget eros. Sed vehicula, metus vel convallis tempus, mauris lorem tristique ipsum, ac condimentum arcu tellus vel nisi. Aliquam mauris est, adipiscing a pharetra ut, molestie egestas mi. Fusce vulputate blandit sagittis. Praesent eget dignissim felis. Integer ac libero eu felis congue cursus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce vel dui a sapien posuere consequat in quis mi. Proin eros nisi, lacinia id tempus id, congue eget justo. Proin ac justo non mi pretium vehicula sed id odio. Vivamus felis nibh, facilisis ut adipiscing at, blandit vitae magna. Praesent tellus est, molestie ut elementum at, pretium nec eros. Etiam diam nisl, varius non gravida eu, facilisis eu nunc.  
  </div>

Seems straightforward enough. We’ve basically just defined a header item for the accordion titles and a content section for each wrapped into a wrapper <div> with the class “accordion”…

With that out of the way, we can give it a little bit of styling using CSS…

.accordion .accordionHeader {
  display: block;
  background: #eee;
  background: #eeeeee -moz-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
  background: #eeeeee -webkit-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
  background: #eeeeee -o-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
  background: #eeeeee -ms-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
  background: #eeeeee linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
  border: 1px solid #ccc;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  padding: 10px;
  font-size: 16px;
  font-weight: normal;
  cursor: pointer;
  margin-bottom: 10px;
}
.accordion .accordionHeader span {
  background: url(images/plus.png) center left no-repeat;
  padding-left: 30px;
}
.accordion .accordionHeader:hover {
  background: #fcfcfc;
}
.accordion .activeItem span {
  background: url(images/minus.png) center left no-repeat;
}
.accordion .accordionContent {
  margin-bottom: 10px;
}

And lastly we can bring it to life with jQuery…

$(document).ready(function () {
    var nbsAccordionSliding = false;
    $('.accordion').find('.accordionHeader').click(function() {
        if(!nbsAccordionSliding) {
            nbsAccordionSliding = true;
            $(this).toggleClass('activeItem') 
            $(this).next().slideToggle({duration: 300, queue: false, easing: 'linear', complete: function() {
                nbsAccordionSliding = false;
            }});
        }
    }).next().hide();
});

UPDATE: What if you wanted to have everything collapse and only show one at a time. To do that, you’ll want to replace the $(document).ready code block with the following…

$(document).ready(function () {
    var nbsAccordionSliding = false;
    $('.accordion').find('.accordionHeader').click(function() {
        $('.accordionHeader').removeClass('activeItem');
        $(this).addClass('activeItem');
        if(!nbsAccordionSliding) {
            nbsAccordionSliding = true;            
            if($(this).next().is(':visible')){            
                $(this).next().slideUp(function(){
                    nbsAccordionSliding = false;                
                });
            }            
            else {
                $('.accordion').find('.accordionHeader').next().slideUp();  
                $(this).next().slideToggle({duration: 300, queue: false, easing: 'linear', complete: function() {
                    nbsAccordionSliding = false;
                }});
            }
        }
    }).next().hide();
});

Click below to view the demo of the final finished product. If you like what you see, you can download the files and use them wherever you like :)

View Demo Download Files

Share Tweet Reccomend

Create a Responsive Tab Box Using jQuery and CSS

Today I am going to show you how to create a tab box using jQuery and CSS. This is certainly a common component found in many websites today. What I like about what we are going to build today is that it gives you a very vanilla boilerplate upon which you can expand. You can add all the styling, colors, and sizing you want on top of this but this will give you a nice starting point. We are also going to be using percentage based width for the components so that you can drop it into any responsive project you are working on.

View Demo Download Files

So let’s get started…

Read More »

Share Tweet Reccomend

Add Simple Infinite Scrolling to Your WordPress Site

This post will show you how to do some simple infinite scrolling for WordPress — or really, with a few small tweaks, any other system for that matter. A lot of times on websites when you have multiple pages of results you will see pagination at the bottom of the page with page 1,2,3 etc. and there will often be first, next, previous and last links in there as well. WordPress does this when blog posts, search results, comments and a number of other sets of results in a WordPress site are broken up into different pages. A lot of WordPress themes will show only the “Previous Posts “and “Next Posts” links by default (referred to as “paging”) but some themes will extend functionality beyond this to full on pagination.

Not all users are super exited about having to click links continuously to go to the next page of results. What infinite scrolling does is get the content found on those pages and append it to the current page so the user never has to click on the pagination links… making for a really nice user experience. You may have seen it on other websites you have visited. This tutorial will show you how to implement it in your own WordPress site.

99% of all WordPress themes’ index.php file has a call to get_header(), get_sidebar() and get_footer() (so I’m kinda assuming yours does as well). In your WordPress theme’s index.php file place the following code right before your call to get_footer();

<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
var currentPage = 2;
var containerItemSelector = "#main";
var postItemSelector = "article";
$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() == $(document).height()) {
    $.ajax({	
      type: "GET",
      url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
      data: "",
      success: function(results) {
        var item = $(containerItemSelector + " > " postItemSelector, results);
        item.each(function() {
          $(containerItemSelector).append($(this));
        });
       currentPage++;
      },
      error: function(results) {
        if(results.status == 404) {
          $(".xhrStatus").html('No more posts to show...');
        }
        else {
          $(".xhrStatus").html('Error retriving posts...');
        }
      }
    });
  }
});
});
</script>

Now, there are a couple of variables that you’ll probably have to change to get infinite scrolling working properly on your site. These are the “containerItemSelector” and the “postItemSelector” variables. You can find them somewhere near the top of the above block of code. These variables tell the infinite scrolling code which container HTML DOM Element to put the next pages of posts in and giving it a wrapper for each post.

Let’s take a look at a very simple sample index.php file to illustrate what is being talked about here…

<?php get_header(); ?>
<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <div class="postContent">
      <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>   
  </div>
  <?php endwhile; ?>
  <?php else: ?>
  <div class="postContent">
    <h2>Not found</h2>
    <p>Sorry, no posts were found</p>
  </div>      
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?> 

So in the instance above, the div with the class “blog” is the wrapper element that we will be adding new posts to and each of those items are contained within a div with a class “postContent”. So we’d want to change our variables to the following…

var containerItemSelector = ".blog";
var postItemSelector = ".postContent";

So the entirety of the code of index.php would look like the following…

<?php get_header(); ?>
<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <div class="postContent">
      <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>   
  </div>
  <?php endwhile; ?>
  <?php else: ?>
  <div class="postContent">
    <h2>Not found</h2>
    <p>Sorry, no posts were found</p>
  </div>      
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
var currentPage = 2;
var containerItemSelector = ".blog";
var postItemSelector = ".postContent";
$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() == $(document).height()) {
    $.ajax({	
      type: "GET",
      url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
      data: "",
      success: function(results) {
        var item = $(containerItemSelector + " > " postItemSelector, results);
        item.each(function() {
          $(containerItemSelector).append($(this));
        });
       currentPage++;
      },
      error: function(results) {
        if(results.status == 404) {
          $(".xhrStatus").html('No more posts to show...');
        }
        else {
          $(".xhrStatus").html('Error retrieving posts...');
        }
      }
    });
  }
});
});
</script>
<?php get_footer(); ?> 

What the code above does is execute an AJAX call to do a “GET” on the next page of results when the user has scrolled to the bottom of the page. The URL that we are getting the results from is represented by the “url” property in the $.ajax block of code. The PHP variable of this property will get the current URL and will get ?paged=[value of the currentPage variable] appended to the end of it. The value of the currentPage variable will start at 2 (since we are already on page 1) and will be incremented every time we do a successful GET of results.

This URL is WordPress’ structure for breaking up content into different pages. If you wanted to add infinite scrolling to a site being run on another system you could use a similar technique, but you’d just have to provide the proper URL for how that system divided things up into pagination.

Note too that we have also added an extra <div> with a class of “xhrStatus” right above the start of our <script> block. We are going to use this div to provide messaging if an error occurs in trying to get the next page of results. If we have reached the end of the results and there are no more posts to show, the server will return a 404 error.

If you wanted to, you could change the HTML element where this message gets displayed. You’d simply have to edit the selector value in jQuery where the message gets outputted to the one that you want.

If you wanted to implement infinite scrolling on different pages (e.g. a page template with custom post type results), you could simply add the above code to that page as well and make any necessary modifications.

Happy scrolling!