Archive for 03/08/14

Tutorial Load Only a Section of a Page

by in , 0

Use Case

You want to AJAX load a section of another page on your site onto the current page. Say your eCommerce CMS system creates a dynamic menu of products, but that exists as a subdirectory of your site and you want to use that on the homepage.

jQuery

$("#mainNav").load("/store #mainNav")

The first param is the URL (only works for same-domain requests!) and the second (well, technically it's still part of the first, separated by a space) is a jQuery selector of the part to load. Not passing the second selector param will load the entire page. There is an optional third parameter, a callback function, which will run when the load is complete.

Reference URL

Tutorial Load jQuery Only If Not Present

by in , 0

Say you were going to do an include on a whole bunch of pages, and inside of that include you wanted to do some jQuery specific stuff. That page may or may not already have jQuery loaded. If it already does, you don't want to load it again, but if not, you do. This works for that.

Smart Asynchronous Way

// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

	if (typeof $ == 'function') {
		// warning, global var
		thisPageUsingOtherJSLibrary = true;
	}
	
	function getScript(url, success) {
	
		var script     = document.createElement('script');
		     script.src = url;
		
		var head = document.getElementsByTagName('head')[0],
		done = false;
		
		// Attach handlers for all browsers
		script.onload = script.onreadystatechange = function() {
		
			if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
			
			done = true;
				
				// callback function provided as param
				success();
				
				script.onload = script.onreadystatechange = null;
				head.removeChild(script);
				
			};
		
		};
		
		head.appendChild(script);
	
	};
	
	getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function() {
	
		if (typeof jQuery=='undefined') {
		
			// Super failsafe - still somehow failed...
		
		} else {
		
			// jQuery loaded! Make sure to use .noConflict just in case
			fancyCode();
			
			if (thisPageUsingOtherJSLibrary) {

				// Run your jQuery Code

			} else {

				// Use .noConflict(), then run your jQuery Code

			}
		
		}
	
	});
	
} else { // jQuery was already loaded
	
	// Run your jQuery Code

};

Notice how there is multiple places the jQuery code you intend to run get's called. Don't repeat yourself there, put it in a function you can call to kick things off.

This code was adapted from here.

Document.write way

Hip kids don't use document.write, but if you are too old to care:

var jQueryScriptOutputted = false;
function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            //output the script (load it from google api)
            document.write("<scr" + "ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
                        
        $(function() {  
            // do anything that needs to be done on document.ready
            // don't really need this dom ready thing if used in footer
        });
    }
            
}
initJQuery();

Tutorial Link Nudging

by in , 0

$("a").hover(function() {
       $(this).stop().animate({paddingLeft : "10px"},200);
},function() {
       $(this).stop().animate({paddingLeft : "0px"},200);
});

Make sure to change the selector to only target the links you want to have nudging, e.g. "#sidebar ul li a"

Tutorial Konami Code

by in , 0

var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";

$(document).keydown(function(e) {

  kkeys.push( e.keyCode );

  if ( kkeys.toString().indexOf( konami ) >= 0 ) {

    $(document).unbind('keydown',arguments.callee);
    
    // do something awesome
    $("body").addClass("konami");
  
  }

});

Tutorial Keep Text Inputs in Sync

by in , 0

var $inputs = $(".example-input");
$inputs.keyup(function() {
      $inputs.val($(this).val());
});

Example



Tutorial jQuery Zebra Stripe a Table

by in , 0

$("tr:odd").addClass("odd");

Then use some CSS:

.odd {
   background: #ccc;
}

Tutorial jQuery Tweetify Text

by in , 0

Function

$.fn.tweetify = function() {
	this.each(function() {
		$(this).html(
			$(this).html()
				.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>')
				.replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
				.replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>')
		);
	});
	return $(this);
}

Usage

$("p").tweetify();

Before

<p>@seanhood have you seen this http://icanhascheezburger.com/ #lol</p>

After

<p><a href="http://twitter.com/seanhood">@seanhood</a> have you seen this
<a href="http://icanhascheezburger.com/">http://icanhascheezburger.com/</a>
<a href="http://search.twitter.com/search?q=%23lol">#lol</a></p>

Reference URL

Tutorial jQuery Sticky Footer

by in , 0

In general the CSS Sticky Footer is the best way to go, as it works perfectly smoothly and doesn't require JavaScript. If the markup required simply isn't possible, this jQuery JavaScript might be an option.

HTML

Just make sure the #footer is the last visible thing on your page.

<div id="footer">
    Sticky Footer
</div>

CSS

Giving it a set height is the most fool-proof.

#footer { height: 100px; }

jQuery

When the window loads, and when it is scrolled or resized, it is tested whether the pages content is shorter than the window's height. If it is, that means there is white space underneath the content before the end of the window, so the footer should be repositioned to the bottom of the window. If not, the footer can retain it's normal static positioning.

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() { 
       
       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");
           
       positionFooter();
       
       function positionFooter() {
       
                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
       
               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }
               
       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)
               
});

Demo

View Demo

Tutorial jQuery Plugin Template

by in , 0

Replace instances of "yourPluginName" with your actual plugin name. The stuff about "radius" is just an example of an option (parameter to pass plugin).

(function($){
    $.yourPluginName = function(el, radius, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        
        // Add a reverse reference to the DOM object
        base.$el.data("yourPluginName", base);
        
        base.init = function(){
            if( typeof( radius ) === "undefined" || radius === null ) radius = "20px";
            
            base.radius = radius;
            
            base.options = $.extend({},$.yourPluginName.defaultOptions, options);
            
            // Put your initialization code here
        };
        
        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        // 
        // };
        
        // Run initializer
        base.init();
    };
    
    $.yourPluginName.defaultOptions = {
        radius: "20px"
    };
    
    $.fn.yourPluginName = function(radius, options){
        return this.each(function(){
            (new $.yourPluginName(this, radius, options));

		   // HAVE YOUR PLUGIN DO STUFF HERE
			
	
		   // END DOING STUFF

        });
    };
    
})(jQuery);

Usage

$(function() {

    $("#round-me").yourPluginName("20px");

});

Reference URL

Tutorial jQuery JSON getting with error catching

by in , 0

jQuery has a built in function called getJSON() to help making AJAX requests for JSON data easier. It normally works great, but if that function gets invalid data (or nothing) back, the callback function will not fire. If there is a legitimate risk of that, you can do this instead to catch for those errors.

$.get('/path/to/url', function (data) {
  if( !data || data === ""){
    // error
    return;
  }
  var json;
  try {
    json = jQuery.parseJSON(data);
  } catch (e) {
    // error
    return;
  }
  
  // use json here
  
}, "text");

Reference URL

Tutorial jQuery Duplicate Plugin

by in , 0

$.fn.duplicate = function(count, cloneEvents) {
       var tmp = [];
       for ( var i = 0; i < count; i++ ) {
               $.merge( tmp, this.clone( cloneEvents ).get() );
       }
       return this.pushStack( tmp );
};

The .clone() function of jQuery will duplicate a set once, but what if you need multiple copies of the same set? You would have to do:

$(elem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem);

Now you can just:

$(elem)
   .duplicate(n)
   .appendTo(otherElem);

The first parameter is the number of clones you want and the second optional parameter is a boolean which controls if you want the events bound to those existing elements to be attached to the clones as well (or not).

Reference URL

Tutorial Insert Element Between Other Elements

by in , 0

For example, if you have five paragraphs in a row and you need to insert a break tag in between all of them. You can't put it before all five (you don't need one at the top) or after all five (you don't need one at the bottom), you only need four.

$("p:not(:last-of-type)").after("<br />");

Tutorial Inputs That Remember Original Value

by in , 0

var origValue = [];
$('input.remember').each ( function (currentIndex)
{
       origValue.push ( $(this).val () );
       $(this).focus ( function ()
       {
               $(this).removeClass("unfocused");
               var defaultText = $(this).val();
               if ( $(this).val () == origValue [ currentIndex ] )
               {
                       $(this).val('');
               }

               $(this).blur(function()
               {
                       var userInput = $(this).val();
                       if (userInput == '')
                       {
                               $(this).val(defaultText);
                               $(this).addClass("unfocused");
                       }
               });
       });
});

A jQuery snippet to make form inputs show a help message which disappears on click (and comes back when the user enters nothing). Give your input the classes 'remember' to activate the snippet and (optionally) 'unfocused' as a CSS hook for changing the styling of the help message.

Tutorial Image Preloader

by in , 0

Very easy way to preload images which are needed later (e.g. when a hover is performed)

<script type="text/javascript">
$.preloadImages = function()
{
       for(var i = 0; i<arguments.length; i++)
       {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function()
{
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});
</script>

Tutorial Highlight Related Label when Input in Focus

by in , 0

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

Tutorial Highlight All Links To Current Page

by in , 0

$(function(){
       $("a").each(function(){
               if ($(this).attr("href") == window.location.pathname){
                       $(this).addClass("selected");
               }
       });
});

This function will add the class "selected" to any links (even relative) that point to the current page.

Tutorial Get X, Y Coordinates of Mouse Within Box

by in , 0

The below code will give you the X, Y coordinates of a mouse click within a given box. Removing all the stuff about the offset, you can easily get the X, Y coordinates of the click relative to the browser window.

$(function() {
$("#demo-box").click(function(e) {

  var offset = $(this).offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);

  alert("X: " + relativeX + "  Y: " + relativeY);

});
});

Example

Click in the box below

Tutorial Get Query Params as Object

by in , 0

Nicholas Ortenzio wrote this little plugin:

jQuery.extend({

  getQueryParameters : function(str) {
	  return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
  }

});

So if the URL is:

http://codepen.io/chriscoyier/pen/uszCr?lunch=sandwich&dinner=stirfry

You can do:

var queryParams = $.getQueryParameters();

And queryParams will be an object like:

{
   "lunch": "sandwich",
   "dinner": "stirfry"
}

Tutorial Get an Images Native Width

by in , 0

If you select and image with jQuery and then use .width(), you'll get the images current width, even if it's been scaled (e.g. max-width: 100%;). You can access the images native width (even if it doesn't have any attributes which declare it) like this:

// Get on screen image
var screenImage = $("#image");

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;

Tutorial Force iframe to Reload

by in , 0

$('iframe').attr('src', $('iframe').attr('src'));

Tutorial Fixing IE z-index

by in , 0

This isn't an end-all-be-all solution to fixing all weird IE z-index issues, but it certainly can help in some circumstances. What it does is loop through each of the elements that you declare and apply ever-declining z-index values on them. IE gets this backwards, and this sets it correctly. The reason it's not end-all-be-all is because sometimes it's not DOM-order that you need z-index to be in, and sometimes scoping comes into play as well.

Nonetheless, the view the demo in IE 7 (thanks Dan Nicholls) to see the broken version on top and the fixed version below.

jQuery Version

$(function() {
       var zIndexNumber = 1000;
       // Put your target element(s) in the selector below!
       $("div").each(function() {
               $(this).css('zIndex', zIndexNumber);
               zIndexNumber -= 10;
       });
});

MooTools Version

if(Browser.Engine.trident){
       var zIndexNumber = 1000;
       // Put your target element(s) in the selector below!
       $$('div').each(function(el,i){
               el.setStyle('z-index',zIndexNumber);
               zIndexNumber -= 10;
       });
};

Reference URL

Tutorial Fixing .load() in IE for cached images

by in , 0

The .load() function fires when the element it's called upon is fully loaded. It is commonly used on images, which may not be fully loaded when the JavaScript originally runs, and thus would return incorrect information about themselves (e.g. height/width). Most browsers deal with this fine. IE can cause problems, when images on the page are cached.

Selecting the image and changing it's src attribute to append a random parameter (based on the date). This will trick IE into firing the .load() function properly.

myImge = $("<img />")
   .attr("src",anyDynamicSource+ "?" + new Date().getTime());

Now the .load() function will work, even in IE:

$(myImge).load(function() {
   alert("will alert even in IE")
});
See the first comment for a warning about using this technique with a CDN.

Tutorial Fix Select Dropdown Cutoff in IE 7

by in , 0

Run (at least the "Usage" part below) after you've loaded jQuery and either at the end of the page or in a DOM ready statement. Note that this fix does create a clone of the select, which will submit itself with the form data, but the name value has been changed to include "-clone" at the end of it, so just be aware of that especially if you are serializing all inputs.

Thanks to Craig Hoover.

// Safely use $
(function($) {

	$.fn._ie_select=function() { 
	
		return $(this).each(function() { 
		
			var a = $(this),
			    p = a.parent();
		
			p.css('position','relative');
		
			var o = a.position(),
			    h = a.outerHeight(),
			    l = o.left,
			    t = o.top;
		
			var c = a.clone(true);
		
			$.data(c,'element',a);
		
			c.css({
				zIndex   : 100,
				height   : h,
				top      : t,
				left     : l,
				position : 'absolute',
				width    : 'auto',
				opacity  : 0
			}).attr({
				id    : this.id + '-clone',
				name  : this.name + '-clone'
			}).change(function() {
				$.data(c,'element')
					.val($(this).val())
					.trigger('change')
			});
				
			a.before(c).click(function() { 
				c.trigger('click');
			});
		
		}); // END RETURN
	
	}; // END PLUGIN
        
        // Usage
	if ($.browser.msie) {
		$('select')._ie_select();
	}

})(jQuery); // END SAFETY

Reference URL

Tutorial Fix Min/Max-Width for Browsers Without Native Support

by in , 0

This script checks all elements with a class of .fixMinMaxwidth and observes the window. It's only applied to browsers without native min/max-width support such as ie6 and below. Window resizing won't be a problem either.

<script type="text/javascript">
//anonymous function to check all elements with class .fixMinMaxwidth
var fixMinMaxwidth=function()
{
       //only apply this fix to browsers without native support
       if (typeof document.body.style.maxHeight !== "undefined" &&
               typeof document.body.style.minHeight !== "undefined") return false;

       //loop through all elements
       $('.fixMinMaxwidth').each(function()
       {
               //get max and minwidth via jquery
               var maxWidth = parseInt($(this).css("max-width"));
               var minWidth = parseInt($(this).css("min-width"));

               //if min-/maxwidth is set, apply the script
               if (maxWidth>0 && $(this).width()>maxWidth) {
                       $(this).width(maxWidth);
               } else if (minWidth>0 && $(this).width()<minWidth) {
                       $(this).width(minWidth);
               }
       });
}

//initialize on domready
$(document).ready(function()
{
       fixMinMaxwidth();
});

//check after every resize
$(window).bind("resize", function()
{
       fixMinMaxwidth();
});
</script>

Reference URL

Tutorial Fire Event When User is Idle

by in , 0

See the two commented lines below, that is where you can insert code for things to do when the user goes idle, and when the user comes back. Set the idle period on the third line, 1000 = 1 second.

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {
    
        $('*').bind('mousemove keydown scroll', function () {
        
            clearTimeout(idleTimer);
                    
            if (idleState == true) { 
                
                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");            
            }
            
            idleState = false;
            
            idleTimer = setTimeout(function () { 
                
                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

                idleState = true; }, idleWait);
        });
        
        $("body").trigger("mousemove");
    
    });
}) (jQuery)

This works by using a setTimeout function to fire at the end of the specified seconds. If basically anything happens during that time (the mouse moves, the page is scrolled, or a key is pressed) the timeout period is reset.

Reference URL

Tutorial Find and Wrap Ampersands

by in , 0

Load this plugin. Then:

$("body *").replaceText( /&/gi, '<b class="ampersand">' + '&' + '</b>' );

Change the selector as needed. That one is pretty intense.

Now you have a class name you can use to style them specially.

.ampersand {
   font-family: Baskerville, Some Other Cool Font, Serif;
   font-style: italic;
}

Reference URL

Tutorial Find all Internal Links

by in , 0

Find all links that start with the sites domain, a slash, relative file path, or a hashtag.

var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

Tutorial Fallback for CDN hosted jQuery

by in , 0

Several big companies offer copies of jQuery hosted on their CDN's (Content Delivery Network). Most notoriously Google, but also Microsoft and jQuery themselves. A lot of people swear by this since it saves bandwidth, downloads faster, and perhaps even stays cached jumping between different sites that use the same script.

There is always that twinge of doubt though, that perhaps something goes wrong with these big companies CDN at the script isn't available (it happens). It's more reliable to use your own website, as hey, if they are loading your webpage, then your server is up and will server the script just fine, albeit with out the benefits of the CDN.

So perhaps the best solution is to use both methods! Use the CDN first, and if it fails, load the local copy. Here is a technique:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='/js/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

Reference URL

Tutorial Fade One Image to Another Menu

by in , 0

Make a CSS sprite image, with the top half and the bottom half being the two images you want to animate between. The jQuery adds a <span> tag, and adds the bottom half of the sprite image as its background. As you hover on and off, the span animates between fully transparent and fully opaque, fading one image into another.

HTML:

<ul id="menu">
       <li id="home"><a href="#">home</a></li>
       <li id="about"><a href="#">about</a></li>
       <li id="services"><a href="#">services</a></li>
       <li id="contact"><a href="#">contact</a></li>
</ul>

CSS:

ul#menu li a{float:left;display:block;background:url("images/menu.png")  no-repeat;width:150px;text-indent:-9999px;height:50px}
ul#menu li#home a{background-position:0px 0px}
ul#menu li#about a{background-position:-150px 0px}
ul#menu li#services a{background-position:-300px 0px}
ul#menu li#contact a{background-position:-450px 0px}

ul#menu li a span {background:url("images/menu.png");height:50px;display:block}
ul#menu li#home a span{background-position:0px -50px}
ul#menu li#about a span{background-position:-150px -50px}
ul#menu li#services a span{background-position:-300px -50px}
ul#menu li#contact a span{background-position:-450px -50px}

jQuery:

$(function() {
       $("ul#menu li a").wrapInner("<span></span>");
       $("ul#menu li a span").css({"opacity" : 0});

       $("ul#menu li a").hover(function(){
               $(this).children("span").animate({"opacity" : 1}, 400);
       }, function(){
               $(this).children("span").animate({"opacity" : 0}, 400);
       });
});

Reference URL

Tutorial Fade Image Into Another Image

by in , 0

Make a div that is the exact size of the image. This div will have a background image applied to it of the second image. Then put an inline image inside it.

<div id="kitten">
    <img src="http://cdn.css-tricks.com/images/kitten.jpg" alt="Kitten" />
</div>

Fading the inline image in and out will reveal/hide the second (background) image.

$("#kitten").hover(function(){

    $(this).find("img").fadeOut();

}, function() {

    $(this).find("img").fadeIn();

});

Tutorial Exclude $(this) from Selector

by in , 0

Let's say you want to attach a click handler to every link on a page. The function for that click handler turns all the other links a different color.

var $allLinks = $("a");

$allLinks.click(function() {

     $allLinks.not(this).css("color", "red");

});

You can use the .not() function to remove elements from a set, so padding this to that function will remove the current element before the color change.

Tutorial Equalize Heights of Divs

by in , 0

var maxHeight = 0;

$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);

Tutorial Draggable without jQuery UI

by in , 0

It doesn't have all the fancy callbacks and options, but hey, it makes things draggable (and with a specified handle optionally).

(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({handle:"",cursor:"move"}, opt);

        if(opt.handle === "") {
            var $el = this;
        } else {
            var $el = this.find(opt.handle);
        }

        return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                var $drag = $(this).addClass('draggable');
            } else {
                var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
            }
            var z_idx = $drag.css('z-index'),
                drg_h = $drag.outerHeight(),
                drg_w = $drag.outerWidth(),
                pos_y = $drag.offset().top + drg_h - e.pageY,
                pos_x = $drag.offset().left + drg_w - e.pageX;
            $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
                $('.draggable').offset({
                    top:e.pageY + pos_y - drg_h,
                    left:e.pageX + pos_x - drg_w
                }).on("mouseup", function() {
                    $(this).removeClass('draggable').css('z-index', z_idx);
                });
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $(this).removeClass('draggable');
            } else {
                $(this).removeClass('active-handle').parent().removeClass('draggable');
            }
        });

    }
})(jQuery);

Usage

$('div').drags();

Demo

Reference URL

Tutorial Display Only First X Divs, Toggle Rest

by in , 0

var news = 2;
hidenews = "- Hide news archive";
shownews = "+ Show news archive";

$(".archive").html( shownews );
$(".news:not(:lt("+news+"))").hide();

$(".archive").click(function (e) {
   e.preventDefault();
       if ($(".news:eq("+news+")").is(":hidden")) {
           $(".news:hidden").show();
           $(".archive").html( hidenews );
       } else {
           $(".news:not(:lt("+news+"))").hide();
           $(".archive").html( shownews );
       }
});

HTML:

<div class="news">First news</div>
<div class="news">Second news</div>
<div class="news">Third news</div>
<a class="archive" href="#"></a>

Reference URL

Tutorial Display Latest FeedBurner Post

by in , 0

This snippet will display the latest post in a specified FeedBurner feed. Just set the URL to your desired FeedBurner feed.

$(document).ready(function(){
       $.ajax({
               type: "GET",
               url: "http://feeds.feedburner.com/examplefeed",
               success: function(data){
                       $("#date").text($(data).find("item:first>pubDate:first").text());
                       $("#title").html("<a href='"+$(data).find("item:first>link:first").text()+"'>"+$(data).find("item:first>title:first").text()+"</a>");
                       $("#description").html($(data).find("item:first>description:first").text());
               }
       });
});

This example assumes that there are 3 elements that this information will be sent to, with the ID attributes set to date, title and description respectively.

Tutorial Display Last Tweet

by in , 0

The code below no longer works as-is with the Twitter API update to 1.1 as of 2013-06-11. The 1.1 API requires oAuth which requires a server side component. Here's a PHP way to interact with the new API. Googling around will find you many other libraries and such. There is an all-JavaScript method for getting tweets, but it may be a bit of a loophole that you may not want to count on.
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/chriscoyier.json?count=1&include_rts=1&callback=?", function(data) {
     $("#twitter").html(data[0].text);
});

Make sure you change username.json to your actual username and #twitter to the actual selector you wish to replace the contents of.

You can play around with this on this CodePen (deprecated).

Tutorial Display Browser and Version

by in , 0

This is jQuery specific, and contains a bit of a hack/fix for dealing with Chrome. This works between jQuery 1.5.1 and jQuery 1.8.3. It's gone in jQuery 1.9. Presumably because it was used too improperly too frequently and it was hurting the web. Better to feature detect when possible.

var userAgent = navigator.userAgent.toLowerCase(),
    browser   = '',
    version   = 0;

$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

// Is this a version of IE?
if ($.browser.msie) {
  userAgent = $.browser.version;
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
  version = userAgent;
  browser = "Internet Explorer";
}

// Is this a version of Chrome?
if ($.browser.chrome) {
  userAgent = userAgent.substring(userAgent.indexOf('chrome/') + 7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
  version = userAgent;
  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
  $.browser.safari = false;
  browser = "Chrome";
}

// Is this a version of Safari?
if ($.browser.safari) {
  userAgent = userAgent.substring(userAgent.indexOf('safari/') + 7);	
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;	
  browser = "Safari";
}

// Is this a version of Mozilla?
if ($.browser.mozilla) {
	//Is it Firefox?
	if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
		userAgent = userAgent.substring(userAgent.indexOf('firefox/') + 8);
		userAgent = userAgent.substring(0,userAgent.indexOf('.'));
		version = userAgent;
		browser = "Firefox"
	}
	// If not then it must be another Mozilla
	else {
	  browser = "Mozilla (not Firefox)"
	}
}

// Is this a version of Opera?
if ($.browser.opera) {
	userAgent = userAgent.substring(userAgent.indexOf('version/') + 8);
	userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	version = userAgent;
	browser = "Opera";
}

// Now you have two variables, browser and version
// which have the right info

Tutorial Disable / Re-enable Inputs

by in , 0

Disable:

$("#submit-button").attr("disabled", true);

Re-enable:

$("#submit-button").removeAttr("disabled");

Tutorial Detect First Visible Element of Certain Class

by in , 0

Adds a class of "first" to the first element that has a class of "activity" that is visible in the browser window.

$(window).scroll(function(){
	var scrollTop = $(window).scrollTop();
	var windowHeight = $(window).height();		
	var first = false;
	$(".activity").each( function() {
		var offset = $(this).offset();
		if (scrollTop <= offset.top && ($(this).height() + offset.top) < (scrollTop + windowHeight) && first == false) {
			$(this).addClass("first");
			first=true;
		} else {
			$(this).removeClass("first");
			first=false;
		}
	});
});

Tutorial Cycle Through a List

by in , 0

This code will cycle through an unordered list with an ID of 'cyclelist'. Can be used on any element with children. Replace "ul#cyclelist li" with the elements you want to cycle through.

$(document).ready(function() {

	 var j = 0;
	 var delay = 2000; //millisecond delay between cycles
	 function cycleThru(){
	         var jmax = $("ul#cyclelist li").length -1;
	         $("ul#cyclelist li:eq(" + j + ")")
	                 .animate({"opacity" : "1"} ,400)
	                 .animate({"opacity" : "1"}, delay)
	                 .animate({"opacity" : "0"}, 400, function(){
	                         (j == jmax) ? j=0 : j++;
	                         cycleThru();
	                 });
	         };

	 cycleThru();

 });
ul#cyclelist {width:200px;border:solid;position:relative;overflow:hidden;height:200px}
ul#cyclelist li {font-size:1.4em;padding:20px;opacity:0;position:absolute}

Reference URL

Tutorial Combine Slide and Fade Functions

by in , 0

$.fn.slideFadeToggle  = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
}; 

Usage

$("#something").click(function() {
   $(this).slideFadeToggle();
});

Tutorial Click Once and Unbind

by in , 0

Have something happen on a click event, but only once! Unbind the click handler after the element has been clicked once.

$('#my-selector').bind('click', function() {
       $(this).unbind('click');
       alert('Clicked and unbound!');
});

Also see Ben's comment below for jQuery's .one() function which is essentially the same thing.

Tutorial Clear Default Search String on Focus

by in , 0

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });
Set value of field to "Search..." When field comes into focus, set color to black. If value is default, remove it. When field goes out of focus, set color back to light gray. If value is empty, put back default value

Tutorial Clear a File Input

by in , 0

You can just clone it and replace it with itself, with all events still attached.

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};

Tutorial Check if jQuery is Loaded

by in , 0

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}

Tutorial Check if Event was Triggered or Native

by in , 0

$('button').click(function(event, wasTriggered) {
    if (wasTriggered) {
        alert('triggered in code');
    } else {
        alert('triggered by mouse');
    }
});

$('button').trigger('click', true);