IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » javascript The latest public javascript snipts.

showing 1-20 of 219 snipts for javascript
  • JS: onfocus and onblur
    $("#email").focus(function() {
        if ($(this).val() == $(this).attr('rel'))
            $(this).val('');
    });
    $("#email").blur(function() {
        if ($(this).val() == '')
            $(this).val($(this).attr("rel"));
    });
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 01, 2010 at 9:54 p.m. EDT
  • Return Input to Default
    /*
     * Return Input Defaults
     *
     * Simply add class="return-value" to any input elements that
     * should clear on focus and return to it's original default
     * value if nothing is entered.
     *
     * Replaces having to do this inline via "onblur" and "onfocus" 
     * methods. <input type="text" value="Search" 
     * onfocus="this.value=(this.value=='Search')?'':this.value"  
     * onblur="this.value=(this.value=='')?'Search':this.value" />
     *
     * Version: 0.1 (last update 09/01/2010)
     * Requires: jQuery v1.4+
     * 
     */
    
    $(document).ready(function() {
    	
    	// need to store default(start) value
    	var $inputs = $(".return-value");
    	var inputArray = new Array();
    	for (i=0; i<$inputs.length; i++) {
    		inputArray[i] = {
    			element : $inputs[i],
    			value : $inputs[i].value
    		};
    	};
    	
    	// clear default value on focus
    	$inputs.focus(function() {
    		if (isDefault(this)) {
    			clearValue(this);
    		};
    	});
    	
    	// input default value on blur
    	var current = 0;
    	$inputs.blur(function() {
    		if (!isDefault(this) && this.value == "") {
    			this.value = inputArray[current].value;
    		};
    		
    	});
    	
    	// is the value of the current element the default value?
    	function isDefault(element) {
    		for (i=0; i<inputArray.length; i++) {
    			if (inputArray[i].value == element.value) {
    				current = i;
    				return true;
    			};
    		};
    		return false;
    	};
    	
    	// clear current value
    	function clearValue(element) {
    		element.value = "";
    	};
    	
    });
    

    copy | embed

    0 comments - tagged in  posted by brandon_rowe on Sep 01, 2010 at 10:28 a.m. EDT
  • String.format() in JS a la Python
    String.prototype.format = function(arguments) {
        var formatted = this;
        for(arg in arguments) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]+'');
        }
        return formatted;
    };
    

    copy | embed

    0 comments - tagged in  posted by sayanriju on Aug 31, 2010 at 8:48 a.m. EDT
  • Get cursor position of clicked mouse on a HTML5 Canvas
    function getCursorPosition(e) {
        var x;
        var y;
        if (e.pageX || e.pageY) {
    	x = e.pageX;
    	y = e.pageY;
        }
        else {
    	x = e.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
    	y = e.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
        }
        // Convert to coordinates relative to the canvas
        x -= gCanvasElement.offsetLeft;
        y -= gCanvasElement.offsetTop;
    
        return [x,y]
    }
    

    copy | embed

    0 comments - tagged in  posted by sayanriju on Aug 31, 2010 at 8:44 a.m. EDT
  • concatObject
    function concatObject(obj) {
        str='';
        for(prop in obj)
        {
            str+=prop + " value :"+ obj[prop]+"\n";
        }
       return(str);
    }
    

    copy | embed

    0 comments - tagged in  posted by toe on Aug 27, 2010 at 10:29 p.m. EDT
  • better tip calculator demo
    <!-- This is a demo for Firefox. There is no error trapping. Forgive me.-->
    <html>
    <head>
    	<title>Tip Calculator</title>
    	<script type="text/javascript">
    		function addit() {
    			var bill = document.getElementById('bill');
    			var tip_pct = document.getElementById('pct');
    			var tip = bill.value * ( tip_pct.value / 100 );
    			// bill.value is actually a string and has to be made into an integer
    			var bill_number = bill.value * 1;
    			// now we need a total
    			var total = bill_number + tip;
    			// Pie charts show proportion, so let's make them for bill and tip as proportion of the total cost (in dollars) after multiplying and rounding to give Google what it needs.
    			var prop_bill = Math.round((bill_number/total)*100);
    			// Since I rounded, I should just do a difference for tip proportion. If I did Math.round again, there is a good likelihood of getting 101 or 99 instead of the 100 wee need for a pie chart.
    			var prop_tip = 100 - prop_bill;
                // I changed the labels to have the propotion values as dollars.
    			document.getElementById('payoff').innerHTML='<img src="http://chart.apis.google.com/chart?chs=500x200&chd=t:' + prop_bill + ',' + prop_tip + '&cht=p&chl=' + prop_bill + '% spent on the food|' + prop_tip + '% spent on the tip" />';
    			// Charts can be tricky to read, so let me dump this out as a sentence
    			document.getElementById('explainer').innerHTML='You are spending a total of <span class="dollars">$' + total + '</span>. Of that, <span class="dollars">$' + bill.value + '</span> is for food and <span class="dollars">$' + tip + '</span> is for the tip.';
    		};
    	</script>
    	<style>
    	    span.dollars{color:#0021a5;}
    	</style>
    </head>
    <body>
    	How much is the bill? <input type="text" id="bill"> <br />
    	How large is the tip? <input type="text" id="pct"> <br />
    	<input type="submit" onClick='addit()'>
        <hr/>
        <!-- I'll make these empty but the elements still exist so I an get them -->
        <p id="explainer"></p>
        <div id="payoff"></div>
    </body>
    

    copy | embed

    0 comments - tagged in  posted by gotoplanb on Aug 26, 2010 at 12:21 p.m. EDT
  • Demo for journprog frontend session
    <html>
    <head>
    	<title>Tip Calculator</title>
    	<script type="text/javascript">
    		function addit() {
    			var bill = document.getElementById('bill');
    			var tip_pct = document.getElementById('pct');
    			var tip = bill.value * ( tip_pct.value / 100 );
    			// alert("The tip amount is: " + tip);
    			document.getElementById('payoff').innerHTML='<img src="http://chart.apis.google.com/chart?chs=500x200&chd=t:' + bill.value + ',' + tip + '&cht=p&chl=Food|Tip" />';
    		};
    	</script>
    </head>
    <body>
    	
    	Bill: <input type="text" id="bill"> <br />
    	Tip Pct: <input type="text" id="pct"> <br />
    	<input type="submit" onClick='addit()'>
        <hr/>
        <div id="payoff">
            I need to make the percents valid.
        </div>
    </body>
    

    copy | embed

    0 comments - tagged in  posted by gotoplanb on Aug 26, 2010 at 12:24 a.m. EDT
  • client-side storage
    // use localStorage for persistent storage
    // use sessionStorage for per tab storage
    textarea.addEventListener('keyup', function () {
      window.localStorage['value'] = area.value;
      window.localStorage['timestamp'] = (new Date()).getTime();
    }, false);
    textarea.value = window.localStorage['value'];
    

    copy | embed

    0 comments - tagged in  posted by ninque on Aug 25, 2010 at 10:14 a.m. EDT
  • new JS selectors in HTML5
    var el = document.getElementById('section1');
    el.focus();
    
    var els = document.getElementsByTagName('div');
    els[0].focus();
    
    var els = document.getElementsByClassName('section');
    els[0].focus();
    
    //by css selectors
    var els = document.querySelectorAll("ul li:nth-child(odd)");
    var els = document.querySelectorAll("table.test > tr > td");
    

    copy | embed

    0 comments - tagged in  posted by ninque on Aug 25, 2010 at 10:10 a.m. EDT
  • Basic Javascript
    Confirm
    
    <script>
    pokracovat = confirm("chcete pokra?ovat?");
    // nyní mám v prom?nné pokracovat uloženo true nebo false
    if(pokracovat) document.write("tak tedy pokra?ujeme");
    </script>
    
    <script src="externi_skript.js"></script>
    
    <a href="http://www.meuslany.cz" onmouseover="alert('Na ú?ad? je myš!!!')">M?stský ú?ad Slaný</a>
    
    <a href="javascript: alert('Toto není odkaz')">Skript</a>
    -----------
    <body>
    <script>
    document.write("ahoj");
    // tento skript se spouští p?i zavád?ní stránky
    </script>
    
    <img src="obrázek.gif" onmouseover="this.src='obrazek2.gif'">
    <!-- obrázek je nahrazen p?i p?ejetí myší -->
    </body>
    ------------
    
    Prefill
    
    <input type="text" value="Sem zadejte text" onfocus="if(this.value=='Sem zadejte text') this.value=''">
    
    ------
    
    <script>
    function noveOkno(soubor)
    {window.open(soubor, "novyRam","width=500,height=400")}
    </script>
    
    a volání funkce navážu na událost kliknutí (onclick) t?eba na obrázku (img):
    
    <img value="Klikni" src="zmensenina1.jpg" onclick="noveOkno('obrazek1.jpg')">
    

    copy | embed

    0 comments - tagged in  posted by ninque on Aug 24, 2010 at 6:39 p.m. EDT
  • Array.map
    Array.prototype.map = function(func) {
      var arr = [];
      for(var i = 0, l = this.length; i < l; i++) {
        arr.push( func.call(this, this[i]) );
      }
      return arr;
    };
    [1,2,3,4].map( function(v) { return v * v * v } );
    

    copy | embed

    0 comments - tagged in  posted by boriscy on Aug 19, 2010 at 12:48 p.m. EDT
  • How to Install Node.js on a Mac
    git clone git://github.com/ry/node.git
    cd node
    ./configure
    make
    sudo make install
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 10, 2010 at 4:39 p.m. EDT
  • Value Labeled Input Box
    <input type="text" value="Search" onfocus="this.value=(this.value=='Search')?'':this.value"  onblur="this.value=(this.value=='')?'Search':this.value" />
    

    copy | embed

    0 comments - tagged in  posted by brandon_rowe on Aug 05, 2010 at 1:21 p.m. EDT
  • Bind event to ajax in building address
    window.onload = function() {
    var myBuildingSelect = document.forms[0].text5;
    var myLocationText = document.forms[0].text3;
    
    if(myBuildingSelect.addEventListener) {
    	myBuildingSelect.addEventListener('change', getLocation, false);
    }
    else if (myBuildingSelect.attachEvent) {
    	myBuildingSelect.attachEvent('onchange', getLocation);
    
    }
    
    
    
    function getLocation(){
      	strBuilding = myBuildingSelect.options[myBuildingSelect.options.selectedIndex].value;
    	new Ajax.Request('http://www.uakron.edu/global/xmlfiles/getbuilding.dot',
      {
    	parameters: { buildingname: strBuilding },
    	method:'get',
    	onSuccess: function(transport){
    	var response = transport.responseText || "";
    	myLocationText.value = response;
                      // alert("Success! \n\n" + response);
        },
    	onFailure: function(){ alert('Something went wrong...') }
      });
    }
    
    }
    

    copy | embed

    0 comments - tagged in  posted by bradrice on Aug 04, 2010 at 1:15 p.m. EDT
  • Immediate callback of a function
    (function(window,document,undefined){
    ……
    })(this,document);
    

    copy | embed

    0 comments - tagged in  posted by joeybaker on Jul 31, 2010 at 9:42 p.m. EDT
  • Build a js object of the cookies in your browser
    function loadCookies() {
    var cr = {}; 
    if (document.cookie != '') {
      var ck = document.cookie.split('; ');
        for (var i=ck.length - 1; i>= 0; i--) {
          var cv = ck[i].split('=');
             cr[cv[0]] = cv[1];
        }
      }
    return cr;
    }
    

    copy | embed

    0 comments - tagged in  posted by bradrice on Jul 23, 2010 at 2:28 p.m. EDT
  • jQuery scrollFollow for minimalists
    /**
     * jquery.scrollstay.js
     * scrollFollow for minimalists.
     *
     * Derived from jquery.scrollFollow.js by R.A. Ray,
     * Copyright (c) 2008 Net Perspective (http://kitchen.net-perspective.com/)
     * Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
     * 
     * Removed all animation, delay, cookies and killSwitch.
     * 
     * @author Dylan McCall
     *
     * @projectDescription	jQuery plugin that quietly keeps an element visible as the user scrolls
     * 
     * @version 0.4.0
     * 
     * @requires jquery.js (tested with 1.2.6)
     * 
     * @param offset			int - Number of pixels box should remain from top of viewport
     * 								default: 0
     * @param container	string - ID of the containing div
     * 								default: box's immediate parent
     * @param relativeTo	string - Scroll animation can be relative to either the 'top' or 'bottom' of the viewport
     * 								default: 'top'
     */
    
    ( function( $ ) {
    	
    	$.scrollStay = function ( box, options ) {
    		// Convert box into a jQuery object
    		box = $( box );
    		
    		// 'box' is the object to be animated
    		var position = box.css( 'position' );
    		
    		function update() {
    			// A bunch of values we need to determine where to animate to
    			var viewportHeight = parseInt( $( window ).height() );
    			var pageScroll =  parseInt( $( document ).scrollTop() );
    			var parentTop =  parseInt( box.cont.offset().top );
    			var parentHeight = parseInt( box.cont.attr( 'offsetHeight' ) );
    			var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
    			var aniTop;
    			
    			/* Make sure the user wants the animation to happen, and it
    			   will be helpful. (It isn't helpful if the user is trying
    			   to scroll within the box!) */
    			if ( viewportHeight > boxHeight ) {
    				// If the box should animate relative to the top of the window
    				if ( options.relativeTo == 'top' ) {
    					// Don't animate until the top of the window is close enough to the top of the box
    					if ( box.initialOffsetTop >= ( pageScroll + options.offset ) ) {
    						aniTop = box.initialTop;
    					} else {
    						aniTop = Math.min( ( Math.max( ( -parentTop ), ( pageScroll - box.initialOffsetTop + box.initialTop ) ) + options.offset ), ( parentHeight - boxHeight - box.paddingAdjustment ) );
    					}
    				}
    				// If the box should animate relative to the bottom of the window
    				else if ( options.relativeTo == 'bottom' ) {
    					// Don't animate until the bottom of the window is close enough to the bottom of the box
    					if ( ( box.initialOffsetTop + boxHeight ) >= ( pageScroll + options.offset + viewportHeight ) ) {
    						aniTop = box.initialTop;
    					} else {
    						aniTop = Math.min( ( pageScroll + viewportHeight - boxHeight - options.offset ), ( parentHeight - boxHeight ) );
    					}
    				}
    				
    				box.css({ top: aniTop });
    			}
    		};
    		
    		// If no parent ID was specified, and the immediate parent does not have an ID
    		// options.container will be undefined. So we need to figure out the parent element.
    		if ( options.container == '') {
    			box.cont = box.parent();
    		} else {
    			box.cont = $( '#' + options.container );
    		}
    		
    		// Finds the default positioning of the box.
    		box.initialOffsetTop =  parseInt( box.offset().top );
    		box.initialTop = parseInt( box.css( 'top' ) ) || 0;
    		
    		// Hack to fix different treatment of boxes positioned 'absolute' and 'relative'
    		if ( box.css( 'position' ) == 'relative' ) {
    			box.paddingAdjustment = parseInt( box.cont.css( 'paddingTop' ) ) + parseInt( box.cont.css( 'paddingBottom' ) );
    		} else {
    			box.paddingAdjustment = 0;
    		}
    		
    		// Animate the box when the page is scrolled
    		$( window ).bind('scroll resize', function () {
    			update();
    		} );
    
    		// Run an initial animation on page load
    		update();
    	};
    	
    	$.fn.scrollStay = function ( options ) {
    		options = options || {};
    		options.relativeTo = options.relativeTo || 'top';
    		options.offset = options.offset || 0;
    		options.container = options.container || this.parent().attr( 'id' );
    		
    		this.each( function() {
    			new $.scrollStay( this, options );
    		} );
    		
    		return this;
    	};
    })( jQuery );
    

    copy | embed

    0 comments - tagged in  posted by dylanmccall on Jul 21, 2010 at 2:16 p.m. EDT
  • Calculate price
    /**
       * Calculates taxi ride price
       *
       * @param Distance of route
       */
      OrderSystem.prototype.calculatePrice = function(distance) {
      	/**
      	 * Each of the pricing arrays consist of three elements:
      	 * 1: kilometers from which the price should be valid
      	 * 2: price per kilometer
      	 * 3: one time price
      	 * The array should be sorted top-down, the longest distance as first element
      	 */
      	var prices = [
      	    [50, 1.45, 0],
      	    [25, 1.75, 0],
      	    [2, 2.2, 0],
      	    [0, 0, 7.5]
      	  ];
      	var totalPrice = 0;
      	
      	for(var x = 0; x < prices.length; x++) {
      		if(distance >= prices[x][0]) {
      			totalPrice += ((distance - prices[x][0]) * prices[x][1]) + prices[x][2];
      			distance = prices[x][0];
      		}
      	}
      	return totalPrice.toFixed(2);
      }
    

    copy | embed

    0 comments - tagged in  posted by dnordstrom on Jul 15, 2010 at 12:03 p.m. EDT
  • blackberry redirect
    <script type="text/javascript">
    	if ((navigator.userAgent.indexOf('BlackBerry') != -1)  ) {
    		document.location = "http://www.yourwebsitename.com/yourwebpagename.html";
    	}
    </script>
    

    copy | embed

    0 comments - tagged in  posted by alexjamalpierce on Jul 07, 2010 at 3:36 a.m. EDT
  • ipad only redirect
    <script type="text/javascript">
    	if ( (navigator.userAgent.indexOf('iPad') != -1)) {
    		document.location = "http://www.youraddress.com/iphone.html";
    	}
    </script>
    

    copy | embed

    0 comments - tagged in  posted by alexjamalpierce on Jul 07, 2010 at 3:31 a.m. EDT
Sign up to create your own snipts, or login.