Showing posts with label jquery. Show all posts

Tutorial Scroll Page Horizontally With Mouse Wheel

by in , 0

1) Load jQuery and the Mouse Wheel plugin

Mouse Wheel plugin is here.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript' src='/js/jquery.mousewheel.min.js'></script>

2) Attach mousewheel event to body

The "30" represents speed. preventDefault ensures the page won't scroll down.

$(function() {

   $("body").mousewheel(function(event, delta) {

      this.scrollLeft -= (delta * 30);
    
      event.preventDefault();

   });

});

View Demo

Tutorial Run JavaScript Only After Entire Page Has Loaded

by in , 0

$(window).bind("load", function() {
   // code here
});

Tutorial Resize iFrame to Fit Content (Same Domain Only)

by in , 0

Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript'>
    
    $(function(){
    
        var iFrames = $('iframe');
      
    	function iResize() {
    	
    		for (var i = 0, j = iFrames.length; i < j; i++) {
    		  iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';}
    	    }
    	    
        	if ($.browser.safari || $.browser.opera) { 
        	
        	   iFrames.load(function(){
        	       setTimeout(iResize, 0);
               });
            
        	   for (var i = 0, j = iFrames.length; i < j; i++) {
        			var iSource = iFrames[i].src;
        			iFrames[i].src = '';
        			iFrames[i].src = iSource;
               }
               
        	} else {
        	   iFrames.load(function() { 
        	       this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
        	   });
        	}
        
        });

</script>

Will resize an iframe like this:

<iframe src="content.html" class="iframe" scrolling="no" frameborder="0"></iframe>

 

View Demo

Still problematic...

The source of the iframe content must reside on the same domain if the content inside the iframe changes height, this won't adapt I left Google Analytics code off the demo above, as when I added it in it seems to interfere and not resize the iframe, despite seemingly generating no errors.

Tutorial Remove Specific Value from Array

by in , 0

var arr = [1, 2, 3, 4, 5];
var removeItem = 2;   
 
arr = $.grep(arr, function(value) {
  return value != removeItem;
});

Tutorial Persistant Headers on Tables

by in , 0

When you scroll down a page with a long table on it, typically the header of the table scrolls away and becomes useless. This code clones the table header and applies it at the top of the page once you have scrolled beyond it, and disappears when you have scrolled past the table.

View Demo

function UpdateTableHeaders() {
   $("div.divTableWithFloatingHeader").each(function() {
       offset = $(this).offset();
       scrollTop = $(window).scrollTop();
       if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
           $(".tableFloatingHeader", this).css("visibility", "visible");
           $(".tableFloatingHeader", this).css("top", Math.min(scrollTop - offset.top, $(this).height() - $(".tableFloatingHeader", this).height()) + "px");
       }
       else {
           $(".tableFloatingHeader", this).css("visibility", "hidden");
           $(".tableFloatingHeader", this).css("top", "0px");
       }
   })
}

$(document).ready(function() {
   $("table.tableWithFloatingHeader").each(function() {
       $(this).wrap("<div class="divTableWithFloatingHeader" style="position:relative"></div>");
       $("tr:first", this).before($("tr:first", this).clone());
       clonedHeaderRow = $("tr:first", this)
       clonedHeaderRow.addClass("tableFloatingHeader");
       clonedHeaderRow.css("position", "absolute");
       clonedHeaderRow.css("top", "0px");
       clonedHeaderRow.css("left", "0px");
       clonedHeaderRow.css("visibility", "hidden");
   });
   UpdateTableHeaders();
   $(window).scroll(UpdateTableHeaders);
});

Reference URL

Tutorial Paste Events

by in , 0

$.fn.pasteEvents = function( delay ) {
    if (delay == undefined) delay = 20;
    return $(this).each(function() {
        var $el = $(this);
        $el.on("paste", function() {
            $el.trigger("prepaste");
            setTimeout(function() { $el.trigger("postpaste"); }, delay);
        });
    });
};

Call this plugin on an element, then you get callback events for before and after pasting:

$("#some-element").on("postpaste", function() { 
    // do something
}).pasteEvents();

Reference URL

Tutorial Password Strength

by in , 0

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

Assumes this HTML:

<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>

Tutorial Partial Page Refresh

by in , 0

Refresh certain elements of a page using jQuery after a set amount of time, can be used with any element with an ID. I amended the example given with the URL to only refresh once and not intermittently. Works in all browsers.

$('#button1').click(function() {

   var url = "http:www.your-url.com?ID=" + Math.random(); //create random number

   setTimeout(function() {
    $("#elementName").load(url+" #elementName>*","");
   }, 1000); //wait one second to run function

});

Reference URL

Tutorial outerHTML jQuery Plugin

by in , 0

innerHTML() is native and returns the contents of a DOM node (e.g. <span>I live inside a div.</span>. outerHTML() is not, which would include the current DOM node (e.g. <div><span>I live inside a div.</span></div>). This is a chain-able jQuery version of doing that.

$.fn.outerHTML = function(){
 
    // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
    return (!this.length) ? this : (this[0].outerHTML || (
      function(el){
          var div = document.createElement('div');
          div.appendChild(el.cloneNode(true));
          var contents = div.innerHTML;
          div = null;
          return contents;
    })(this[0]));
 
}

Reference URL

Tutorial Open External Links In New Window

by in , 0

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.

Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.

$("#content a[href^='http://']").attr("target","_blank");

Also note that there are a wide variety of different ways to only target external links.

Tutorial Move Cursor To End of Textarea or Input

by in , 0

jQuery.fn.putCursorAtEnd = function() {

  return this.each(function() {

    $(this).focus()

    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;

      this.setSelectionRange(len, len);
    
    } else {
    // ... otherwise replace the contents with itself
    // (Doesn't work in Google Chrome)

      $(this).val($(this).val());
      
    }

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;

  });

};
Check out this Pen!

Reference URL

Tutorial Move Clicked List Items To Top Of List

by in , 0

Assuming HTML like this:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

So if "Two" is clicked, move it to the top of the list.

$("li").click(function() {
     
  $(this).parent().prepend($(this));
  
});

Will work for multiple lists...

Tutorial Make jQuery :contains Case-Insensitive

by in , 0

// NEW selector
jQuery.expr[':'].Contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

// OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

Update to work for jQuery 1.8

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

With this in place,

$("div:contains('John')")

would select all three of these elements:

<div>john</div>
<div>John</div>
<div>hey hey JOHN hey hey</div>

Demo via Pablo Fortes.

Tutorial Make Entire Div Clickable

by in , 0

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Looks for a link inside div with class of "myBox". Redirects to that links value when anywhere in div is clicked.

Reference HTML:

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a>
</div>

Tutorial Loading jQuery

by in , 0

Load with Google API

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
    google.load("jquery", "1.2.6");
</script>
<script type="text/javascript" src="js/example.js"></script>

Direct Link to Google

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>

Check if loaded, only load if unloaded

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
       });
   }

}

Reference URL

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