Never been to DZone Snippets 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

« Newer Snippets
Older Snippets »
Showing 11-20 of 435 total

Extending Array Prototype

Extending array prototype with sum, minimum, maximum and remove

Array.prototype.sum = function(){
	for (var i=0, sum=0; i < this.length; sum += this[i++]);
	return sum;
}
Array.prototype.max = function(){
	return Math.max.apply({},this)
}
Array.prototype.min = function(){
	return Math.min.apply({},this)
}
Array.prototype.remove=function(s){
	for (i=0; i < this.length; i++){
		if (s == this[i]) this.splice(i, 1);
	}
}

Preloading Images with jQuery

Taken from http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery

jQuery.preloadImages = function() {
	for (var i = 0; i < arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

Creating Tabs with Forms in JQuery

// An example of a tabbed form in JQuery UI, based on the example file
// Requires the following files to run: jquery-1.2.6.js, ui.core.js,
// ui.tabs.js, flora.tabs.css, flora.css, i/tabs.png


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <title>Using JQuery Tabs</title>

      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="expires" content="0">
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
      <meta http-equiv="description" content="This is my page">


      <link rel="stylesheet" href="flora.tabs.css" type="text/css"
         media="screen" title="Flora Tabs">
      <script type="text/javascript" src="jquery-1.2.6.js"></script>
      <script type="text/javascript" src="ui.core.js"></script>
      <script type="text/javascript" src="ui.tabs.js"></script>
      <script type="text/javascript"> 
                                        
 $(document).ready(function() {
   
   $("#example > ul").tabs();
   
   // if tab is pressed from these fields, show the next tab
   $("input#zipCode,input#notificationDate").bind("keydown", function(e) {
      var keynum;
      var keychar;
      var numcheck;
    
      if(window.event) // IE
          {
          keynum = e.keyCode;
          }
      else if(e.which) // Netscape/Firefox/Opera
          {
          keynum = e.which;
          }
      keychar = String.fromCharCode(keynum);
      numcheck = /\t/;    
      if (numcheck.test(keychar)) {  //it's a tab
         selectNextTab();
         setFocus();
      }
   });

 });
 
 
 
function selectNextTab() {
    var $tabs = $('#example > ul').tabs();
    var selected = $tabs.data('selected.tabs');
    
    switch(selected) {
        case 0:
            $('#example > ul').tabs('select', 1);
            break;
        
        case 1:
            $('#example > ul').tabs('select', 2);
            break;
        
        case 2: 
            $('#example > ul').tabs('select', 3);
            break;
    
    }
}
 
 function setFocus() {
    var $tabs = $('#example > ul').tabs();
    var selected = $tabs.data('selected.tabs');
    
    switch(selected) {
        case 1:
            $('input#notificationtype').select();
            break;
        
        case 2:
            $('input#householdIncome').select();
            break;
        
        case 3: 
            $('input#testInput').select();
            break;
    }

 
 }
                             
 </script>
   </head>
   <body>

      <div id="example" class="flora">
         <ul>

            <li>
               <a href="#fragment-1"><span>The first thing</span> </a>
            </li>
            <li>
               <a href="#fragment-2"><span>Second Thing</span> </a>
            </li>
            <li>
               <a href="#fragment-3"><span>Thing Three</span> </a>
            </li>
         </ul>
         <div id="fragment-1">
            <table width="98%" align="center">
               <tr>
                  <td width="10%">
                     Address 1
                  </td>
                  <td>
                     <input type="text" id="address1" name="address1"
                        tabindex="1" size="45">
                  </td>
               </tr>
               <tr>
                  <td>
                     Address 2
                  </td>
                  <td>
                     <input type="text" name="address2" tabindex="2"
                        size="45">
                  </td>
               </tr>
               <tr>
                  <td>
                     City
                  </td>
                  <td>
                     <input type="text" name="city" tabindex="3">
                  </td>
                  <td>
                     State
                  </td>
                  <td>
                     <select tabindex="4">
                        <option>
                           Florida
                        </option>
                        <option>
                           New York
                        </option>
                     </select>
                  </td>
                  <td>
                     Zip Code
                  </td>
                  <td>
                     <input type="text" id="zipCode" name="zipCode"
                        tabindex="5">
                  </td>
               </tr>
            </table>


         </div>
         <div id="fragment-2">
            <table width="98%" align="center">
               <tr>
                  <td width="20%">
                     <span style="text-decoration: none; color: black;">
                        Notification Type</span>
                  </td>
                  <td colspan="2">
                     <input type="text" id="notificationtype"
                        tabindex="6">
                  </td>
                  <td>
                     <span style="color: black">Notificaton Date</span>
                  </td>
                  <td colspan="1">
                     <input type="text" id="notificationDate"
                        name="notificationDate" tabindex="7">
                  </td>
               </tr>
            </table>

         </div>
         <div id="fragment-3">
            <table width="98%" align="center">
               <tr>
                  <td width="20%">
                     <span style="text-decoration: none; color: black;">Test
                        Select</span>
                  </td>
                  <td colspan="2">
                     <select id="testSelect" tabindex="8">
                        <option>
                           One thing
                        </option>
                        <option>
                           The other Thing
                        </option>
                     </select>
                  </td>
                  <td>
                     <span style="color: black">Test Input</span>
                  </td>
                  <td colspan="1">
                     <input type="text" id="testInput" name="testInput"
                        tabindex="9">
                  </td>
               </tr>
            </table>
         </div>
      </div>


   </body>
</html>

Disable auto complete in input form

Disable auto complete in input form.

<script type="text/javascript">

window.onload = function() {
	for(var i = 0, l = document.getElementsByTagName('input').length; i < l; i++) {
		if(document.getElementsByTagName('input').item(i).type == 'text') {
			document.getElementsByTagName('input').item(i).setAttribute('autocomplete', 'off');
		};
	};
};

<script>


Source AB-D: Disable autocomplete in input type="text"

Rewrite input to friendly URL

// Take an input and rewrite it to a friendly-url-like-this

<script type="text/javascript">

	// Store the current title value
	var title = 'This is a title with a symbol &'

	// alert(title); // debug

	// Clean up the title		
	var url = title
		.toLowerCase() // change everything to lowercase
		.replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces		
		.replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
		.replace(/[^a-z0-9-]+/g, "") // remove all non-alphanumeric characters except the hyphen
		.replace(/[-]+/g, "-") // replace multiple instances of the hyphen with a single instance
		.replace(/^-+|-+$/g, "") // trim leading and trailing hyphens				
		; 
	
	alert(url); // outputs 'this-is-a-title-with-a-symbol'

</script>

Stopping double submits



        Dim sb As New System.Text.StringBuilder()
        sb.Append("if (typeof(Page_ClientValidate) == 'function') { ")
        sb.Append("if (Page_ClientValidate() == false) { return false; }} ")
        sb.Append("this.value = 'Please Wait...';")
        sb.Append("this.disabled = true;")
        sb.Append(Me.Page.GetPostBackEventReference(Me.btnSubmit))
        sb.Append(";")
        btnSubmit.Attributes.Add("onclick", sb.ToString())

Setting focus to a field in asp.net

This code does a simple field focus in asp.net.

    Protected Sub setFieldFocus(ByVal ctrl As System.Web.UI.Control)
        Dim s As String = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ClientID + "').focus() </SCRIPT>"
        ClientScript.RegisterStartupScript(Me.GetType, "focus", s)
    End Sub

     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindData()
        End If
        setFieldFocus(txtSpecies)
    End Sub

Send a request by YUI

// description of your code here

<script type="text/javascript" src="<c:url value="/yui/yahoo-dom-event/yahoo-dom-event.js"/>"></script>
<script type="text/javascript" src="<c:url value="/yui/utilities/utilities.js"/>"></script>
<script type="text/javascript" src="<c:url value="/yui/dom/dom.js"/>"></script>
<script language="javascript">
<!--
var Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Connect = YAHOO.util.Connect;
function loadGoodsNameList(goodsType){
	if(goodsType==0||goodsType==1602){
		return;
	}
	var uri = "<c:url value="/lgt/util.do?m=listGoodsName&goodsType="/>"+goodsType+ "&timestamp=" + new Date().getTime(); 
	Connect.asyncRequest("GET",uri,{
		success:function(o){
			Dom.get('goodsName').parentNode.innerHTML = "<select name='modelId' id='goodsName' style='width: 200px;'>"+o.responseText+"</select>";
		},
		failure : function(o) {
			alert(o.status);
			alert(o.statusText);
			alert(o.responseText);
		},
		argument : null});
}
//-->
</script>

Fix PNG transparent IE6

function fixPNG() {
	if(navigator.appName == 'Microsoft Internet Explorer') {
		var png = /\.png$/i;
		var imgs = document.getElementsByTagName('img');
		for(var i = 0, l = imgs.length; i < l; i++) {
			if(png.test(imgs.item(i).src)) {
				imgs.item(i).style.width = imgs.item(i).offsetWidth;
				imgs.item(i).style.height = imgs.item(i).offsetHeight;
				imgs.item(i).style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + imgs.item(i).src + '\',sizingMethod=\'image\')';
				imgs.item(i).src = 'empty.gif';
			}
		}
	}
}


Retour à la source : PNG transparent 24 bits for Internet Explorer 6

Image Rotate with CANVAS

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>rotate()</title>
	
	<style type="text/css" media="screen">
	img, canvas { border: 1px solid black; }
	</style>


<script type="text/javascript">

function rotate(p_deg) {
	if(document.getElementById('canvas')) {
		/*
		Ok!: Firefox 2, Safari 3, Opera 9.5b2
		No: Opera 9.27
		*/
		var image = document.getElementById('image');
		var canvas = document.getElementById('canvas');
		var canvasContext = canvas.getContext('2d');
		
		switch(p_deg) {
			default :
			case 0 :
				canvas.setAttribute('width', image.width);
				canvas.setAttribute('height', image.height);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, 0, 0);
				break;
			case 90 :
				canvas.setAttribute('width', image.height);
				canvas.setAttribute('height', image.width);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, 0, -image.height);
				break;
			case 180 :
				canvas.setAttribute('width', image.width);
				canvas.setAttribute('height', image.height);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, -image.width, -image.height);
				break;
			case 270 :
			case -90 :
				canvas.setAttribute('width', image.height);
				canvas.setAttribute('height', image.width);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, -image.width, 0);
				break;
		};
		
	} else {
		/*
		Ok!: MSIE 6 et 7
		*/
		var image = document.getElementById('image');
		switch(p_deg) {
			default :
			case 0 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
				break;
			case 90 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
				break;
			case 180 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
				break;
			case 270 :
			case -90 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
				break;
		};
		
	};
};


window.onload = function() {
	var image = document.getElementById('image');
	var canvas = document.getElementById('canvas');
	if(canvas.getContext) {
		image.style.visibility = 'hidden';
		image.style.position = 'absolute';
	} else {
		canvas.parentNode.removeChild(canvas);
	};
	
	rotate(0);
};

</script>

</head>

<body>


<p>
	rotate:
	<input type="button" value="" onclick="rotate(0);" />
	<input type="button" value="90°" onclick="rotate(90);" />
	<input type="button" value="180°" onclick="rotate(180);" />
	<input type="button" value="-90°" onclick="rotate(-90);" />
</p>


<p>
	<img id="image" src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="" />
	<canvas id="canvas"></canvas>
</p>


</body>
</html>


Source: AB-D.fr - Effectuer une rotation d'image en CSS ( rotate balise canvas HTML5 )
« Newer Snippets
Older Snippets »
Showing 11-20 of 435 total