Sign up to create your own snipts, or login.

Public snipts » javascript The latest public javascript snipts.

showing 1-20 of 152 snipts for javascript
  • center div both horizontal and vertical
    .className{
    	margin:0 auto;
    	width:200px;
    	height:200px;
    }
    
    .className{
    	width:300px;
    	height:200px;
    	position:absolute;
    	left:50%;
    	top:50%;
    	margin:-100px 0 0 -150px;
    }
    
    $(window).resize(function(){
    
    	$('.className').css({
    		position:'absolute',
    		left: ($(document).width() - $('.className').outerWidth())/2,
    		top: ($(document).height() - $('.className').outerHeight())/2
    	});
    
    });
    
    // To initially run the function:
    $(window).resize();
    

    copy | embed

    0 comments - tagged in  posted by keyboardkitteh on Mar 06, 2010 at 4:38 a.m. EST
  • Disallow doubleclick of form submit buttons
    // Find ALL <form> tags on your page
    $('form').submit(function(){
      // On submit disable its submit button
      $('input[type=submit]', this).attr('disabled', 'disabled');
    });
    

    copy | embed

    0 comments - tagged in  posted by bwsewell on Mar 05, 2010 at 12:09 p.m. EST
  • Button to launch X-ray popup
    <a href="#" style="background-color: rgba(23,110,107,.3); color: #000; text-decoration: none;" onClick="myRef = window.open('http://poynterextra.org/xray/roy_AppForThat','xraywindow','left=20,top=20,width=900,height=500,toolbar=0,scrollbars=1');myRef.focus()">See the X-ray reading by Roy Peter Clark</a>
    

    copy | embed

    0 comments - tagged in  posted by gotoplanb on Mar 03, 2010 at 12:02 p.m. EST
  • 2
    action: $('form#newHotnessForm').attr('action'),
    

    copy | embed

    0 comments - tagged in  posted by mkelly12 on Feb 26, 2010 at 6:47 p.m. EST
  • 1
    new AjaxUpload('imageUpload', {
    

    copy | embed

    0 comments - tagged in  posted by mkelly12 on Feb 26, 2010 at 6:14 p.m. EST
  • The trim function that should have always been
    /*	Trim
    
    	Adds/enables the trim function to strings.
    	
    	This makes sure the user's browser isn't already using the
    	ES 5 (next version of JS) trim function.
    */
    if (typeof String.prototype.trim !== 'function') {
    	String.prototype.trim = function () {
    		return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by scoot2006 on Feb 24, 2010 at 10:34 a.m. EST
  • See the comments in the code...
    /*	Supplant
    
    Replaces items in a string denoted with curly braces with their associated values in an object.
    
    Example:
    
    Say you have a markup template like:
    
    	var template =	'<table border="{border}">' +
    						'<thead>' +
    							'<tr>' +
    								'<th>First</th>' +
    								'<th>Last</th>' +
    							'</tr>' +
    						'</thead>' +
    						'<tbody>' +
    							'<tr>' +
    								'<td>{first}</td>' +
    								'<td>{last}</td>' +
    							'</tr>' +
    						'</tbody>' +
    					'</table>';
    					
    And an object like this:
    					
    	var data = {
    		first: "John",
    		last: "Smith",
    		border: 1
    	};
    
    This function will replace all instances of "{border}" with 1,
    all instances of "{first}" with John, and all instances of
    "{last}" with Smith.
    
    Example call:
    
    	mydiv.innerHTML = template.supplant(data);
    
    */	
    if (typeof String.prototype.supplant !== 'function') {
    	String.prototype.supplant = function (o) {
    		return this.replace(/{([^{}]*)}/g,
    			function (a, b) {
    				var r = o[b];
    				return typeof r === 'string' ? r : a;
    			});
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by scoot2006 on Feb 24, 2010 at 10:33 a.m. EST
  • Checks to see if an object is an array.
    /*	Array.isArray
    	
    	Checks to see if the passed object is an array since typeof(array) === 'object'
    	
    	Makes sure the user's browser isn't using the ES 5 isArray function.
    */
    if (typeof Array.isArray !== 'function') {
    	Array.isArray = function (value) {
    		return Array.prototype.toString.apply(value) === '[object Array]';
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by scoot2006 on Feb 24, 2010 at 10:32 a.m. EST
  • Some JS for Flot with some Rails to flavor
    /* Generate Graph of Weights for <%= @user.name %> as provided in @DataSet */
    var underweight = $("#bmi_underweight").css("background-color");
    var normalweight =  $("#bmi_normalweight").css("background-color");
    var overweight =  $("#bmi_overweight").css("background-color");
    var obese =  $("#bmi_obese").css("background-color");
    
    
    $.plot($("#weight_chart"),[{label: "Weight", data:<%= @DataSet.to_json %>}],
        {
          series: {
            color: "#000000",
            lines: {
              show: true,
              fill: false,
              lineWidth: 5
              },
            shadowSize: 10,
            points: { show: true }
          },
          grid: {
            hoverable: true, clickable: true ,
            backgroundColor: { colors: ["#fff", "#eee"] },
            markings: [
              { yaxis: { <%= @bmi_ranges["underweight"] %>}, color:underweight },
              { yaxis: {  <%= @bmi_ranges["normal"] %> }, color:normalweight },
              { yaxis: {  <%= @bmi_ranges["overweight"] %> }, color:overweight },
              { yaxis: {  <%= @bmi_ranges["obese"] %> }, color:obese }
              ]
          },
          xaxis: {
            mode: "time",
            timeformat: "%b %d, %y"
          }
      });
    

    copy | embed

    0 comments - tagged in  posted by lear64 on Feb 23, 2010 at 11:00 a.m. EST
  • submit a form when a hyperlink or image is clicked
    // Sample code 1: pure PHP and javascript
    <form name="myform" action="handle-data.php">
    Search: <input type='text' name='query' />
    <a href="javascript: submitform()">Search</a>
    </form>
    <script type="text/javascript">
    function submitform()
    {
      document.myform.submit();
    }
    </script> 
    
    //Sample code 2: symfony and jQueryHelper
    // form to submit
    <form action="<?php echo url_for('semester/batchDelete') ?>" name="batchform" method="post">
    </form>
    //define a method to submit form in javascript
    <?php echo javascript_tag("
      function submitBatchForm(){
        document.batchform.submit();
      }
    ") ?>
    <?php echo jq_link_to_function('delete selection', 'submitBatchForm()') ?>
    

    copy | embed

    0 comments - tagged in  posted by toledot on Feb 19, 2010 at 4:13 p.m. EST
  • Navigon Connect Code for Mobile Safari
    javascript:window.location='navigon://NAVIGON%7CCoordinates%7C%7C%7C%7C%7C%7C'+gApplication.getMap().getCenter().lng()+'%7C'+gApplication.getMap().getCenter().lat()
    

    copy | embed

    0 comments - tagged in  posted by binaryghost on Jan 27, 2010 at 11:30 a.m. EST
  • nodelist to array usinf prototype
    NodeList.prototype.toArray = function()
    {
    	var ary = [];
    	for(var i=0, len = this.length; i < len; i++)
    	{
    		ary.push(this[i]);
    	}
    	return ary;
    };
    
    //call like this
    var elements = document.querySelectorAll('a').toArray(); 
    

    copy | embed

    0 comments - tagged in  posted by Yansky on Jan 23, 2010 at 8:03 p.m. EST
  • convert nodelist to array
    [].slice.call(document.querySelectorAll('a'), 0).forEach(function(element, index, array){
      console.log(element);
    });
    

    copy | embed

    0 comments - tagged in  posted by Yansky on Jan 23, 2010 at 8:01 p.m. EST
  • it returns randomly "yes" or "no"
    Math.round(Math.random()) ? "yes" : "no";
    

    copy | embed

    0 comments - tagged in  posted by marcell on Jan 11, 2010 at 8:03 a.m. EST
  • Create Dropdown from Select (JS)
    function createDropSelect(){
    	var count = 0;
    	$('.select').each(function(){
    		var select = $(this),
    			selected = select.find("option[selected]"),
    			options = $("option", select);
    		
    		$(".attr_values").append('<dl class="dropselector '+ count +' right"></dl>');
    		$(".dropselector."+count).append('<dt><a href="#" class="call">' + selected.text() + 
    			'<span class="value">' + selected.val() + 
    			'</span></a></dt>')
    		$(".dropselector."+count).append('<dd><ul class="call"></ul></dd>')
    		
    		options.each(function(){
    			if( $(this).text() == selected.text()){
    				$(".dropselector."+count+" dd ul").append('<li class="current"><a href="#">' +
    					$(this).text() + '<span class="value">' + 
    					$(this).val() + '</span></a></li>');
    			}else{
    				$(".dropselector."+count+" dd ul").append('<li><a href="#">' + 
    					$(this).text() + '<span class="value">' + 
    					$(this).val() + '</span></a></li>');
    			}
    		});
    		count++;
    	})
    }
    createDropSelect();
    $(".dropselector dt a").click(function() {
    	$(this).parent().parent().children('dd').children('ul').toggle();
    });
    $(".dropselector dd ul li a").click(function() {
    	var text = $(this).html();
    	$(this).parents('.dropselector').children('dt').children('a').html(text);
    	$(this).parents('.dropselector').children('dd').children('ul').toggle();
    	
    	var source = $(".select");
    	source.val($(this).find("span.value").html())
    });
    $(document).bind('click', function(e) {
    	var $clicked = $(e.target);
    	if (! $clicked.parents().hasClass("dropselector"))
    		$(".dropselector dd ul").hide();
    });
    

    copy | embed

    0 comments - tagged in  posted by styledev on Jan 01, 2010 at 6:16 p.m. EST
  • Javascript image replacement based on class name
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script type="text/javascript">
    
     $(document).ready(function() {
      var tcells = document.getElementsByTagName("td");
      for (i=0;i<tcells.length;i++) {
       var tcell = tcells.item(i);
       if (tcell.className == "status") {
        if (tcell.innerHTML == "Open") tcell.innerHTML = '<img src="/image/open.gif" />';
         else if (tcell.innerHTML == "Closed") tcell.innerHTML = '<img src="/images/open.png" />';
       }
      }
      return false;
     });
    </script>
    

    copy | embed

    0 comments - tagged in  posted by terramar on Dec 29, 2009 at 2:38 p.m. EST
  • Clear Input Using Prototype, Part II
    <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
    	document.observe('dom:loaded', function() {
    
    		// Get all input elements with input class;
    		var blurElements = $$('input.input');
    
    		// Create global scope for storing default values;
    		var scope = {};
    
    		// Iterate through all targeted elements;
    		for (var idx = 0, len = blurElements.length; idx < len; idx++) {
    			var el = blurElements[idx];
    			scope[el.identify()] = el.value;
    			el.observe('blur', function(event) {
    				var e = event.element();
    				var defaultValue = this[e.identify()];
    				if(e.value == '' || e.value == defaultValue) {
    					e.value = defaultValue;
    				}
    			}.bindAsEventListener(scope));
    
    			el.observe('focus', function(event) {
    				var e = event.element();
    				if (e.value == this[e.identify()]) {
    					e.clear();
    				}
    			}.bindAsEventListener(scope));
    		}
    	});
    </script>
    

    copy | embed

    0 comments - tagged in  posted by ritcheyer on Dec 28, 2009 at 6:35 p.m. EST
  • Clear Input using Prototype
    <script type="text/javascript" charset="utf-8">
    	/* -------------------------------------------------------------------------------
    	As it turns out, this way isn't as efficient as initially thought. Yes, the code
    	is small and light (not as light as jQuery, but that's another topic entirely. As
    	I understand it, the 'click' and 'blur' will always fire regardless of where you
    	click on the page. If you are concerned about how many times users click on your
    	page, I suggest looking at Part II:
    	http://snipt.net/ritcheyer/clear-input-using-prototype-part-ii
    	------------------------------------------------------------------------------ */
    
    	document.observe('click',function(event) {
    		var e = event.element();
    		var defaultValue = e.value;
    		if(e.match('input[class="input"]')) {
    
    			// -- clear input field
    			e.clear();
    
    		}
    	
    		// -- if input looses focus replace value
    		e.observe('blur', function() {
    			if(e.value == '' || e.value == defaultValue) {
    				e.value = defaultValue;
    			}
    		});
    	});
    </script>
    

    copy | embed

    0 comments - tagged in  posted by ritcheyer on Dec 28, 2009 at 6:04 p.m. EST
  • Replacement to target="_blank"
    $("a[@rel~='external']").click( function() {
        window.open( $(this).attr('href') );
        return false;
    });
    

    copy | embed

    0 comments - tagged in  posted by twofivethreetwo on Dec 15, 2009 at 10:38 a.m. EST
  • Checking if a variable was previously defined
    //This will check if variable "variable" was previously defined
    (typeof(variable) != "undefined")
    

    copy | embed

    0 comments - tagged in  posted by brenes on Dec 14, 2009 at 10:22 a.m. EST
Sign up to create your own snipts, or login.