Public
snipts » javascript
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(); -
∞ 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'); });
-
∞ 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>
-
∞ 2
action: $('form#newHotnessForm').attr('action'),
-
∞ 1
new AjaxUpload('imageUpload', {
-
∞ 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"); } }
-
∞ 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; }); } }
-
∞ 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]'; } }
-
∞ 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" } });
-
∞ 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()') ?>
-
∞ 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()
-
∞ 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();
-
∞ convert nodelist to array
[].slice.call(document.querySelectorAll('a'), 0).forEach(function(element, index, array){ console.log(element); });
-
∞ it returns randomly "yes" or "no"
Math.round(Math.random()) ? "yes" : "no";
-
∞ 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(); });
-
∞ 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>
-
∞ 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>
-
∞ 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>
-
∞ Replacement to target="_blank"
$("a[@rel~='external']").click( function() { window.open( $(this).attr('href') ); return false; });
-
∞ Checking if a variable was previously defined
//This will check if variable "variable" was previously defined (typeof(variable) != "undefined")



Pro JavaScript Techniques