Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

javascript email address validation with regular expression



email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
  // Yay! valid
  return true;
}
else
  {return false;}

Dump a Javascript Object


// thanks: http://weblogs.asp.net/skillet/archive/2006/03/23/440940.aspx

var MAX_DUMP_DEPTH = 10;
function dumpObj(obj, name, indent, depth) {
if (depth > MAX_DUMP_DEPTH) {
return indent + name + ": <Maximum Depth Reached>\n";
}
if (typeof obj == "object") {
var child = null;
var output = indent + name + "\n";
indent += "\t";
for (var item in obj)
{
try {
child = obj[item];
} catch (e) {
child = "<Unable to Evaluate>";
}
if (typeof child == "object") {
output += dumpObj(child, item, indent, depth + 1);
} else {
output += indent + item + ": " + child + "\n";
}
}
return output;
} else {
return obj;
}
}

Watch YouTube videos with QuickTime

Requires SIMBL and GreaseKit. Tested on Safari.
# YouTube in MP4 via QuickTime Plugin!
# http://www.joeyhagedorn.com/2008/04/16/youtube-in-mp4-via-quicktime-plugin

open -a Safari http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js


# Download YouTube Videos as MP4 Files
# http://googlesystem.blogspot.com/2008/04/download-youtube-videos-as-mp4-files.html

open -a Safari http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js


1. Youtube QT (http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js)
// ==UserScript==
// @name           Youtube QT
// @namespace      userscripts.org
// @description    Plays the high-resolution YouTube video in an embedded Quicktime player 
// @version        0.1
// @include        http://youtube.com/watch?*
// @include        http://www.youtube.com/watch?*
// @include        http://*.youtube.com/watch?*
// ==/UserScript==
	
var video_id = null;
var video_hash = null;
var video_player = document.getElementById('movie_player');

if (video_player) {var flash_variables=video_player.attributes.getNamedItem('flashvars');
	if (flash_variables) {var flash_values=flash_variables.value;
		if (flash_values) {var video_id_match=flash_values.match(/video_id=([^(\&|$)]*)/);
			if (video_id_match!=null) video_id=video_id_match[1];
				var video_hash_match=flash_values.match(/t=([^(\&|$)]*)/);
				if (video_hash_match!=null) video_hash=video_hash_match[1];
		}
	}
}

if (video_id==null || video_hash==null) {var args=unsafeWindow.swfArgs;
	if (args) {video_id=args['video_id'];
		video_hash=args['t'];
	}
}

if (video_id==null || video_hash==null) return;

var yt_mp4_path = 'http://www.youtube.com/get_video?fmt=18&video_id='+video_id+'&t='+video_hash;
var div_embed=document.getElementById('watch-player-div');

if (div_embed) {div_embed.innerHTML='<embed src=\''+yt_mp4_path+'\' type="video/mp4" width=480 height=400 scale=\'aspect\'></embed>';
};


2. Download YouTube Videos as MP4 (http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js)
// ==UserScript==
// @name           Download YouTube Videos as MP4
// @description    Adds an option to download YouTube videos.
// @namespace      http://googlesystem.blogspot.com
// @include        http://*.youtube.com/watch?*
// @include        http://youtube.com/watch?*
// @version        0.4
// ==/UserScript==

if ( navigator.userAgent.indexOf("AppleWebKit") != -1 ) {
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = window.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }

} else {
    (function () {
    
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = unsafeWindow.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }
      
    })();
}

Adding input:focus functionality to IE using prototype.js

  Event.observe(window, 'load', function() {
    var fields = $$("input");
    for (var i = 0; i < fields.length; i++) {
      fields[i].onfocus = function() {this.className += ' focused';}
      fields[i].onblur = function() {this.className = this.className.replace('focused', '');}
    }
  });


in the css file:

input:focus,   /* works in FF without javascript */
input.focused  /* used by js */
   { background-color: #f7cd72; }

jQuery accordion

jquery accordion
<script type="text/javascript" >
$(document).ready(function(){
    lastBlock = $("#a1");
    maxWidth = 210;
    minWidth = 75;	

    $("ul li a").hover(
      function(){
        $(lastBlock).animate({width: minWidth+"px"}, { queue:false, duration:400 });
	$(this).animate({width: maxWidth+"px"}, { queue:false, duration:400});
	lastBlock = this;
      }
    );
});
</script>

ul{
  list-style: none;
  margin: 0;
  padding: 0;
}

ul li{
  float: left;
  padding: 10px;
  display: block;
  margin-right: 10px;
}

ul li a{
  display: block;
  overflow: hidden;
  height: 75px;
  width: 75px;
}

#a1{
  width: 210px;
}

ul li img{
  position: absolute;
  border: 3px solid #881212;
}

ul li p{
  margin: 0;
  padding: 0;
  width: 120px;
  display: block;
  margin-left: 85px;
}

<ul>
  <li>
    <a id="a1">
      <img src="images/free_thumb.jpg" />
      <p>
        <strong>Freebies</strong><br/>
        Download free files to make your job easier.
      </p>
    </a>
  </li>
  <li>
    <a>
       <img src="images/tut_thumb.jpg" />
       <p>
         <strong>Tutorials</strong><br/>
         Tips and tricks to help you
         keep up with the latest technology.
       </p>
    </a>
  </li>
  <li>
    <a>
      <img src="images/inspire_thumb.jpg" />
      <p>
        <strong>Inspiration</strong><br/>
        Get inspired by what other designers are doing.
      </p>
    </a>
  </li>
</ul>

check an age to see if they meet a minimum requirement

// description of your code here

		
		formMonth = $("#edit-profile-birth-date-month").val();
		formDay = $("#edit-profile-birth-date-day").val();
		formYear = $("#edit-profile-birth-date-year").val();	
		currentMonth = 10;
		currentDay = 24;
		currentYear = 2008;
	
		requiredAge = 13;
		oldEnough = false;
		nonSafeYear = currentYear - requiredAge;
	
		//do the age validation logic here
		if(formYear <  nonSafeYear){
			oldEnough = true;
		
		}else if(formYear == nonSafeYear){
		
			// check month
			if(formMonth > currentMonth){
				oldEnough = true;
	
			}else if(formMonth == currentMonth){
	
				//check day
				if(formDay > currentDay){
					oldEnough = true;
				}
			
			}
			
		}

Javascript open new window with all params

function pop_window()
{
window.open ("http://url.com","Window Title","status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1, scrollbars=0,height=0,width=0");
}


Rails link to helper
<%= link_to "link text", {:action => "help"}, :popup => ['Terms and Conditions','width=400,height=400'] %>

javascript dispatch mouse event

var button = document.evaluate("//button[text()='archive']", document, null, XPathResult.ANY_TYPE,null).iterateNext();
var evt = document.createEvent("MouseEvents"); 
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
button.dispatchEvent(evt);


http://developer.mozilla.org/En/DOM:document.createEvent

Get Selected Option Text From HTML Select List



var select_list_field = document.getElementById('field_id');
var select_list_selected_index = select_list_field.selectedIndex;

var text = select_list_field.options[select_list_selected_index].text;
var value = select_list_field.value;