Tutorial Smarter Event Binding

by in , 0

$("p").live("click", function(){
      $(this).css("color", "red");
});

The reason this is smarter is because there are likely many p elements on the page. If there were, say, 10 of them, traditional click event binding would require 10 handlers. The live function only requires one, reducing memory needed by the browser. Then imagine compounding the issue by 100 (for example, a table with 1000 cells with hover events).

Additionally, using the live function does not require events to be re-bound when additional elements are added to the page (like via AJAX).

Reference URL

Tutorial Sliding Background Links

by in , 0

$('a', '#nav').hover(function() {
         if(!$(this).parent().hasClass('current')) {
                 $(this).stop().animate({
                         backgroundPosition: '(0 -75px)'
                 });
         }
 }, function() {
         if(!$(this).parent().hasClass('current')) {
                 $(this).stop().animate({
                         backgroundPosition: '(0 -0)'
                 });
         }
 });

Slides up and down the background image of a link when rolled over. Requires background position plugin.

Tutorial Simple jQuery Accordion

by in , 0

jQuery

Make sure either to run on DOM ready or at the bottom of the page.

(function($) {
    
  var allPanels = $('.accordion > dd').hide();
    
  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });

})(jQuery);

HTML

<dl class="accordion">

<dt><a href="">Panel 1</a></dt>
<dd>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</dd>

<dt><a href="">Panel 2</a></dt>
<dd>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</dd>

<dt><a href="">Panel 3</a></dt>
<dd>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</dd>

</dl>

SCSS

Sorry if you don't use SASS. Should be pretty easy to convert.

.accordion {
   margin: 50px;   
   dt, dd {
      padding: 10px;
      border: 1px solid black;
      border-bottom: 0; 
      &:last-of-type {
        border-bottom: 1px solid black; 
      }
      a {
        display: block;
        color: black;
        font-weight: bold;
      }
   }
  dd {
     border-top: 0; 
     font-size: 12px;
     &:last-of-type {
       border-top: 1px solid white;
       position: relative;
       top: -1px;
     }
  }
}

View Demo

Slightly more advanced, preventing closing of active panel:

View Demo

Tutorial Simple Auto-Playing Slideshow

by in , 0

HTML

Wrapper with div's as the "slides", which can contain any content.

<div id="slideshow">
   <div>
     <img src="http://farm6.static.flickr.com/5224/5658667829_2bb7d42a9c_m.jpg">
   </div>
   <div>
     <img src="http://farm6.static.flickr.com/5230/5638093881_a791e4f819_m.jpg">
   </div>
   <div>
     Pretty cool eh? This slide is proof the content can be anything.
   </div>
</div>

CSS

Slides need to be absolutely positioned within the wrapper. This has a tiny bit of extra pizazz:

#slideshow { 
    margin: 50px auto; 
    position: relative; 
    width: 240px; 
    height: 240px; 
    padding: 10px; 
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 
}

#slideshow > div { 
    position: absolute; 
    top: 10px; 
    left: 10px; 
    right: 10px; 
    bottom: 10px; 
}

jQuery JavaScript

Run after DOM is ready.

$("#slideshow > div:gt(0)").hide();

setInterval(function() { 
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
},  3000);

See it

View Demo

Very similar one from Snook.

Tutorial Shuffle DOM Elements

by in , 0

This is from James Padolsey. Check out his article for a pure JavaScript technique as well.

Plugin

(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);

Usage

Target elements, call shuffle.

$('ul#list li').shuffle();

Tutorial Shuffle Children

by in , 0

Nice clean version of a ghetto one that I wrote.

$.fn.shuffleChildren = function() {
    $.each(this.get(), function(index, el) {
        var $el = $(el);
        var $find = $el.children();

        $find.sort(function() {
            return 0.5 - Math.random();
        });

        $el.empty();
        $find.appendTo($el);
    });
};

Usage

$(".parent-element").shuffleChildren();

View Demo

Tutorial Show Most Recent Picasaweb Uploads

by in , 0

Replace the "tester" username below with your own, and the target value with the selector of the element you wish to append the pictures to.

$(document).ready(function() {
	$.getJSON("http://picasaweb.google.com/data/feed/base/user/tester/?kind=photo&access=public&alt=json&callback=?",
	function(data) {
		var target = "#latest-picasaweb-images ul"; // Where is it going?
		for (i = 0; i <= 9; i = i + 1) { // Loop through the 10 most recent, [0-9]
			var pic = data.feed.entry[i].media$group;
			var liNumber = i + 1; // Add class to each LI (1-10)
			var thumbSize = 0; // Size of thumbnail - 0=small 1=medium 2=large
			$(target).append("<li class='no-" + liNumber + "'><a title='" + pic.media$description.$t + "' href='" + pic.media$content[0].url + "'><img src='" + pic.media$thumbnail[thumbSize].url + "' /></a></li>");
		}
	});
});

Example

Reference URL