Category Archives: javascript

Link Alert con MooTools

 
var LinkAlert = new Class({
 
	//implements
	Implements: [Options,Events],
 
	//options
	options: {
		container: document.body,
		extensions: {},
		offsets: { x:6, y:-15 },
		preloadImages: true,
		protocols: {},
		sticky: false,
		onShow: function(el,image) {
			this.image.setStyle('display','');
		},
		onHide: function(el,image) {
			this.image.setStyle('display','none');
		}
	},
 
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		this.extensions = new Hash(this.options.extensions);
		this.protocols = new Hash(this.options.protocols);
		this.image = new Element('img',{
			src: '',
			styles: {
				position: 'absolute',
				top: -200,
				left: -200,
				visibility: 'hidden'
			}
		}).inject(document.id(document.body));
		//preload images, if necessary
		if(this.options.preloadImages) { this.preloadImages(); }
		//add the listeners
		this.addListeners(this.extensions,'$=','extensions');
		this.addListeners(this.protocols,'^=','protocols');
	},
 
	//give direction to links
	addListeners: function(items,sep,type) {
		//for every item
		items.each(function(image,extension,type) {
			//for every link of that type
			$$('a[href' + sep + '\'' + extension + '\']').each(function(el) {
				//if the same protocol, don't bother showing
				if(type == 'protocol' && window.location.protocol == extension + ':') { return; }
				//add the show/hide events
				el.addEvents({
					mouseenter: function(e) {
						//position the image and give it the proper SRC
						this.reposition(e).set('src',image);
						//fire the event
						this.fireEvent('show',[el,image]);
					}.bind(this),
					mouseleave: function(e) {
						//fire the event
						this.fireEvent('hide',[el,image]);
					}.bind(this)
				});
				//sticky?
				if(this.options.sticky) {
					el.addEvent('mousemove',function(e) {
						this.reposition(e);
					}.bind(this));
				}
			},this);
		},this);
	},
 
	//repositions
	reposition: function(e) {
		return this.image.setStyles({
			left: e.page.x + this.options.offsets.x,
			top: e.page.y + this.options.offsets.y
		});
	},
 
	//preloads necessary images
	preloadImages: function() {
		var images = [this.protocols.getValues(),this.extensions.getValues()].flatten();
		new Asset.images(images);
	}
});
 

ESEMPIO APPLICATO

 
/* do it */
window.addEvent('domready', function() {
	var graphicsDir = 'link-alert/';
	var context = new LinkAlert({
		extensions: {
			doc: graphicsDir + 'word.png',
			js: graphicsDir + 'js.png',
			pdf: graphicsDir + 'pdf.png',
			txt: graphicsDir + 'text.gif',
			xls: graphicsDir + 'xls.png',
			jpg: graphicsDir + 'jpg.png'
		},
		protocols: {
			ftp: graphicsDir + 'ftp.png',
			https: graphicsDir + 'secure.png',
			'javascript:': graphicsDir + 'js.png'
		},
		preloadImages: true,
		sticky: true,
		onShow: function(el,image) {
			this.image.fade('in');
		},
		onHide: function(el,image) {
			this.image.fade('out');
		}
	});
});
 

Demo: http://davidwalsh.name/dw-content/link-alert.php

[jQuery] Usare l’opacitÓ per concentrarsi su un singolo elemento!

 
$(document).ready(function() {
	//area 1
	$('.fade-area-1').children().hover(function() {
		$(this).siblings().stop().fadeTo(500,0.5);
	}, function() {
		$(this).siblings().stop().fadeTo(500,1);
	});
	//area 2
	$('.fade-area-2').children().hover(function() {
		$(this).siblings().stop().fadeTo(500,0.5);
	}, function() {
		$(this).siblings().stop().fadeTo(500,1);
	});
});
 

Demo: http://davidwalsh.name/dw-content/fade-except-jquery.php

Animazione opacitÓ con jQuery

CODICE HTML

 
<div id="forest-slot-1" class="opacity">
	<h2>The Forest</h2>
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus viverra ipsum at est condimentum sed ultricies turpis pellentesque. Proin scelerisque malesuada erat, id sagittis enim auctor vitae. Sed eget nisl ipsum, quis eleifend lacus. Aenean at erat nulla, id semper velit.</p>
</div>
<div id="forest-slot-2" class="opacity">
	<h2>The Jungle</h2>
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus viverra ipsum at est condimentum sed ultricies turpis pellentesque. Proin scelerisque malesuada erat, id sagittis enim auctor vitae.</p>
</div>
<div id="forest-slot-3" class="opacity">
	<h2>The Wildlife</h2>
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus viverra ipsum at est condimentum sed ultricies turpis pellentesque. Proin scelerisque malesuada erat, id sagittis enim auctor vitae.</p>
</div>
 

CODICE CSS

 
/* all css is specific to THIS example */
#forest		{ width:800px; height:360px; position:relative; background:url(forest.jpg) 0 bottom no-repeat; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; }
.opacity	{ background:#fff; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; padding:20px; }
#forest-slot-1	{ height:260px; position:absolute; top:20px; left:20px; width:340px; }
#forest-slot-2	{ height:100px; position:absolute; top:20px; right:20px; width:310px; }
#forest-slot-3	{ height:100px; position:absolute; top:180px; right:20px; width:310px; }
 

CODICE JAVASCRIPT

 
$(document).ready(function() {
	//settings
	var opacity = 0.7, toOpacity = 0.9, duration = 250;
	//set opacity ASAP and events
	$('.opacity').css('opacity',opacity).hover(function() {
			$(this).fadeTo(duration,toOpacity);
		}, function() {
			$(this).fadeTo(duration,opacity);
		}
	);
});
 

Lava Lamp menu in jQuery

CODICE HTML

 
<div id="lava">
 
	<ul>
		<li><a href="#">home</a></li>
		<li><a href="#">lava lamp menu</a></li>
		<li><a href="#">queness.com</a></li>
		<li class="selected"><a href="#">jQuery</a></li>			
	</ul>
 
	<!-- If you want to make it even simpler, you can append these html using jQuery -->
	<div id="box"><div class="head"></div></div>
 
</div>
 

CODICE CSS

 
	body {
		font-family:georgia; 
		font-size:14px; 
	}
	a {
		text-decoration:none; 
		color:#333;
	}
 
	#lava {
		/* you must set it to relative, so that you can use absolute position for children elements */
		position:relative; 
		text-align:center; 
		width:583px; 
		height:40px;
	}
 
	#lava ul {
		/* remove the list style and spaces*/
		margin:0; 
		padding:0; 
		list-style:none; 
		display:inline;
 
		/* position absolute so that z-index can be defined */
		position:absolute; 
 
		/* center the menu, depend on the width of you menu*/
		left:110px; 
		top:0; 
 
		/* should be higher than #box */
		z-index:100;
 
	}
 
	#lava ul li {
 
		/* give some spaces between the list items */
		margin:0 15px; 
 
		/* display the list item in single row */
		float:left;
	}
 
	#lava #box {
 
		/* position absolute so that z-index can be defined and able to move this item using javascript */
		position:absolute; 
		left:0; 
		top:0; 
 
		/* should be lower than the list menu */
		z-index:50; 
 
		/* image of the right rounded corner */
		background:#ccc; 
		height:20px;
 
		/* add padding 8px so that the tail would appear */
		padding-right:8px;
 
		/* self-adjust negative margin to make sure the box display in the center of the item */
		margin-left:-10px;
	}
 
	#lava #box .head {
		/* image of the left rounded corner */
		background:#eee;
		height:20px;
 
		/* self-adjust left padding to make sure the box display in the center of the item */
		padding-left:10px;
	}
 

CODICE JAVASCRIPT

 
 
	$(document).ready(function () {
 
		//transitions
		//for more transition, goto http://gsgd.co.uk/sandbox/jquery/easing/
		var style = 'easeOutElastic';
 
		//Retrieve the selected item position and width
		var default_left = Math.round($('#lava li.selected').offset().left - $('#lava').offset().left);
		var default_width = $('#lava li.selected').width();
 
		//Set the floating bar position and width
		$('#box').css({left: default_left});
		$('#box .head').css({width: default_width});
 
		//if mouseover the menu item
		$('#lava li').hover(function () {
 
			//Get the position and width of the menu item
			left = Math.round($(this).offset().left - $('#lava').offset().left);
			width = $(this).width(); 
 
			//Set the floating bar position, width and transition
			$('#box').stop(false, true).animate({left: left},{duration:1000, easing: style});	
			$('#box .head').stop(false, true).animate({width:width},{duration:1000, easing: style});	
 
		//if user click on the menu
		}).click(function () {
 
			//reset the selected item
			$('#lava li').removeClass('selected');	
 
			//select the current item
			$(this).addClass('selected');
 
		});
 
		//If the mouse leave the menu, reset the floating bar to the selected item
		$('#lava').mouseleave(function () {
 
			//Retrieve the selected item position and width
			default_left = Math.round($('#lava li.selected').offset().left - $('#lava').offset().left);
			default_width = $('#lava li.selected').width();
 
			//Set the floating bar position, width and transition
			$('#box').stop(false, true).animate({left: default_left},{duration:1500, easing: style});	
			$('#box .head').stop(false, true).animate({width:default_width},{duration:1500, easing: style});		
 
		});
 
	});
 

Troncare una stringa in jQuery

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.truncate.js"></script>
 

 
<p class="myClass">
 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam fringilla, purus a ultrices blandit,
 odio ante scelerisque neque, vitae imperdiet odio velit ac nisl. Sed tortor metus, placerat condimentum,
 feugiat in, feugiat adipiscing, mi. Donec pulvinar sem vitae leo. eget lectus et ligula hendrerit
</p>
 

per applicare il plugin basterÓ aggiungere

 
$(function {
  $(".myClass").truncatable();
});
 

Scarica il codice sorgente

Anteprima dei commenti con mootools

CODICE HTML

 
<div id="live-preview-form" class="lp-block">
	<p>
		<strong>Your Name:</strong><br />
		<input type="text" name="name" id="name" value="" class="input" /><br /><br />
		<strong>Your Email:</strong><br />
		<input type="text" name="email" id="email" value="" class="input" /><br /><br />
		<strong>Your Website:</strong><br />
		<input type="text" name="website" id="website" value="" class="input" /><br /><br />
		<strong>Your Comment:</strong><br />
		<textarea name="comment" id="comment" class="input" rows="10"></textarea>
	</p>
</div>
 
<div id="live-preview-display" class="lp-block">
	<div id="lp-avatar"></div>
	<div id="lp-name"></div>
	<div id="lp-comment"></div>
</div>
 

CODICE CSS

 
.lp-block		{ width:400px; float:left; }
.lp-block input, .lp-block textarea { width:90%; }
#live-preview-display 	{ background:#eee; padding:10px; margin-left:50px; margin-top:20px; }
 
#lp-name { font-weight:bold; }
#lp-avatar { float:right; margin:0 0 20px 20px; }
#lp-comment { padding-top:10px; font-style:italic; line-height:19px; }
 

CODICE JAVASCRIPT/MOOTOOLS

 
(function($){
	window.addEvent('domready',function(){
		//the build process
		var build = function() {
			//vars (fields) and blocks
			var lpcomment = $('lp-comment'), lpname = $('lp-name'), lpavatar = $('lp-avatar');
			var name = $('name'), email = $('email'), website = $('website'), comment = $('comment');
 
			//comment
			lpcomment.set('text',comment.value);
			lpcomment.set('html',lpcomment.get('html').replace(/\n/g,'<br />'));
 
			//name & websites
			if(website.value && (website.value).test(/http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/)) {
				lpname.set('html','<a href="' + website.value + '">' + name.value + '</a> says:');
			}
			else {
				lpname.set('text',name.value + ' says:');
			}
			//gravatar
			if(email.value && (email.value).test(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)) {
					var md5Email = MD5(email.value);
					lpavatar.set('html','<img src="http://www.gravatar.com/avatar.php?gravatar_id=' + md5Email + '&size=80&rating=G&default=http%3A%2F%2Fdavidwalsh.name%2Fwp-content%2Fthemes%2Fdavid-walsh%2Fgraphics%2Fcom.jpg" alt="' + lpname + '" />');
			}
		};
		//comment...easy
		$$('#live-preview-form input, #live-preview-form textarea').addEvents({
			keyup: build,
			blur: build
		});
	});
})(document.id);
 

Convertire i secondi in formato time con PHP & JS

CODICE PHP

 
function formatTime($secs) {
   $times = array(3600, 60, 1);
   $time = '';
   $tmp = '';
   for($i = 0; $i < 3; $i++) {
	  $tmp = floor($secs / $times[$i]);
	  if($tmp < 1) {
		 $tmp = '00';
	  }
	  elseif($tmp < 10) {
		 $tmp = '0' . $tmp;
	  }
	  $time .= $tmp;
	  if($i < 2) {
		 $time .= ':';
	  }
	  $secs = $secs % $times[$i];
   }
   return $time;
}
 

CODICE JAVASCRIPT

 
function formatTime(secs){
   var times = new Array(3600, 60, 1);
   var time = '';
   var tmp;
   for(var i = 0; i < times.length; i++){
	  tmp = Math.floor(secs / times[i]);
	  if(tmp < 1){
		 tmp = '00';
	  }
	  else if(tmp < 10){
		 tmp = '0' + tmp;
	  }
	  time += tmp;
	  if(i < 2){
		 time += ':';
	  }
	  secs = secs % times[i];
   }
   return time;
}
 

Come potete vedere le funzioni sono identiche, dovete solo scegliere (in base alle vostre esigenze) quale delle due applicare

Aggiungere record a una coda con jQuery

CODICE HTML

 
< !DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<title>jQuery Add to Queue</title>
</head>
<body>
<h1>jQuery Add to Queue</h1>
<form id="form" method="post" action="process.php">
  <label for="input">Add to queue:</label>
  <input type="text" name="input" id="input"/>
  <input type="submit" name="Submit" id="submit" value="Add!"/>
</form>
<h2>Queue: </h2>
<div id="queue"></div>
</body>
 
 

CODICE CSS

 
#queue {
	background-color: #CCCCCC;
	padding: 6px;
	border: 1px solid #000000;
}
#queue > div {
	background-color: #66CC66;
	border: 1px solid #FFFFFF;
	margin: 4px;
	padding: 4px;
	display: none;
}
 

CODICE JAVASCRIPT

 
$(document).ready(function() {
   // wait for form submission
   $("#form").submit(function() {
	  // get the input element and text
	  var input = $("#input");
	  var text = input.val();
	  // check if text was entered
	  if(text.length > 0) {
		 // create a new div element, add it to queue and animate
		 var element = $('<div>' + text + '</div>');
		 element.prependTo("#queue").slideDown();
		 // clear input field
		 input.val('');
	  }
	  // prevent default form action
	  return false;
   });
});
 

AGGIUNGIAMO L'AJAX

 
$(document).ready(function() {
   // wait for form submission
   $("#form").submit(function() {
	  // get the input element and text
	  var input = $("#input");
	  var text = input.val();
	  // check if text was entered
	  if(text.length > 0) {
		 //post data to process.php and get json
		 $.post('process.php', { data: text }, function(data) {
			// if process.php returns success
			if(data.status == 'success') {
			   // create a new div element, add it to queue and animate
			   var element = $('<div>' + data.text + '</div>');
			   element.prependTo("#queue").slideDown();
			   // clear input field
			   input.val('');
			}
		 }, 'json');
	  }
	  // prevent default form action
	  return false;
   });
});
 

FILE process.php

 
< ?php
if(isset($_POST['data'])) {
   // add to database or something here
   $text = htmlspecialchars($_POST['data']);
   echo "{'status':'success','text':'" . $text . "'}";
}
else {
   echo "{'status':'failed'}";
}
?>
 

Cufon, qualsiasi font sulle vostre pagine web!

Cufon Ŕ uno script molto utilie in quanto riesce a sostituire il font i sistema con quello desiderato.

Per prima cosa scaricate lo script: http://cufon.shoqolate.com/js/cufon-yui.js

 
<script type="text/javascript" src="javascript/cufon.js"></script>
 

Adesso generate con questo tool il js del font: http://cufon.shoqolate.com/generate/

ESEMPIO APPLICATO:

 
<script type="text/javascript">
  Cufon.replace(['h1','p']);
</script>
 

Per far si che su explorer aumenti la velocitÓ d rendering inserite questo dopo il tag body:

 
<!--[if IE]>
  <script type="text/javascript"> Cufon.now(); </script>
< ![endif]-->