Showing posts with label jquery. Show all posts

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