Tag Archive for javascript

Load Specific Stylesheets for iPhone depending on Orientation

<link rel="stylesheet" type="text/css" href="stylesheets/iphone_portrait.css" id="orient_css">

<script type="text/javascript" charset="utf-8">
function orient()
{
switch(window.orientation){
case 0: document.getElementbyId("orient_css").href = "stylesheets/iphone_portrait.css";
break;

case -90: document.getElementbyId("orient_css").href = "stylesheets/iphone_landscape.css";
break;

case 90: document.getElementbyId("orient_css").href = "stylesheets/iphone_landscape.css";
break;
}
}
window.onload = orient();
</script>

<body onorientationchange="orient();">

source

Hide iPhone Address Bar Once Page is Loaded

<script type="text/javascript" charset="utf-8">
addEventListener('load', function() {
setTimeout(hideAddressBar, 0);
}, false);
function hideAddressBar() {
window.scrollTo(0, 1);
}
</script>

source

Javascript Tag Cloud

/**----------------------------------------------------------------
*
*  TAG CLOUD IMPLEMENTATION
*
*///--------------------------------------------------------------
var TagCloud = function(){

var DEFAULT_UNIT = '%';
var DEFAULT_TEXT_PROPERTY = 'text';
var DEFAULT_VALUE_PROPERTY = 'value';

var gatherStatistics = function(data, config){

var currentMax = data[0][config.valueProperty];
var currentMin = data[0][config.valueProperty];

for(var i = 0; i < data.length; i++){
var value = data[i][config.valueProperty];

currentMax = (currentMax < value)?value:currentMax;
currentMin = (currentMin > value)?value:currentMin
}

return {
max  : currentMax,
min  : currentMin,
mid  : (currentMax+currentMin)/2,
unit : (currentMax-currentMin)/100
};
}

var defaultScaler = function(value, rangeData){
return ((value/rangeData.max)*100)+100;
}

return {
process : function(data, config){
config = config || {};

config.unit = config.unit || DEFAULT_UNIT;
config.textProperty = config.textProperty || DEFAULT_TEXT_PROPERTY;
config.valueProperty = config.valueProperty || DEFAULT_VALUE_PROPERTY;

var dataRange = gatherStatistics(data, config);
var scaler = config.scaler || defaultScaler;

for(var i = 0; i < data.length; i++){
var scale = scaler(data[i][config.valueProperty], dataRange);
config.renderer(data[i][config.textProperty], scale, config.unit);
}
}
}
}();

/**----------------------------------------------------------------
*
*  BASIC USAGE EXAMPLE
*
*///--------------------------------------------------------------
var cloudData = [
{text:"One", value:41},
{text:"Two", value:122},
{text:"Three", value:53},
{text:"Four", value:45},
{text:"Five", value:52},
{text:"Six", value:68}
];

TagCloud.process(cloudData,{
renderer : function(text, size, unit){
document.write("<span style="font-size:" + size + unit + ";">" + text + "</span>");
}
,scaler : function(value, rangeData){

var MAXFONTSIZE = 30;
var MINFONTSIZE = 12;

var spread = rangeData.max - rangeData.min;

if(spread == 0){
spread = 1;
}

return MINFONTSIZE + (value - rangeData.min) *
(MAXFONTSIZE - MINFONTSIZE) / spread;

}
,unit : 'px'
});

source

Two Lists

//******************************************************************************
// Función nativa de Javascript que se ha modificado por otra.
// Elimina un (o mas) elemento(s) de un array:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
//******************************************************************************

/*
* 		Clase Two_lists
*
* 		Permite que interactuen 2 elementos SELECT y 2 elementos INPUT del TYPE=BUTTON, para que
* 		que los elementos OPTION de dentro de los SELECT, puedan moverse de un SELECT a otro.
* 		Para hacer el movimiento, se selecciona el OPTION y se pulsa el botón correspondiente.
* 		También se puede hacer seleccionando múltiples OPTIONs con las teclas Ctrl o Shift, siempre
* 		que el SELECT tenga MULTIPLE=MULTIPLE. Para mover uno de manera más práctica, haciendo doble
* 		click también se moverá de SELECT.
*
* 		Para instanciar la clase, hay que pasar cuatro parámetros :
* 		* El primer SELECT
* 		* El segundo SELECT
* 		* El INPUT que mueve del primer SELECT al segundo
* 		* El INPUT que mueve del segundo SELECT al primero
*
* 		La clase posee cuatro funciones a parte de la constructora:
* 		* moveOptionToSelect2 (option)
* 			Mueve el option a nivel interno, es decir, en las 2 arrays internas con los datos de todos
* 			los OPTIONS, mueve el item referenciado al option de un array al otro, y después elimina el
* 			option del HTML.
* 		* moveOptionToSelect1 (option)
* 			Idem anterior, pero en el otro sentido.
* 		* updateSelect1 ()
* 			Actualiza los OPTIONs del primer SELECT, según el array interno referenciado a ese SELECT.
* 			Vacía el SELECT, y lo rellena creando los OPTIONS con sus datos.
* 		* updateSelect2 ()
* 			Idem anteior, pero en el segundo SELECT.
*
*/

var Two_lists = new Class({
Implements: [Options],

select1 : 	null,
select2 : 	null,
asignar :	null,
liberar :	null,
options1 : 	new Array(),		// Array interno con los datos de los OPTIONs del primer SELECT
options2 : 	new Array(),		// Array interno con los datos de los OPTIONs del segundo SELECT

options: {},

//***********************************
// INITIALIZE
//	Función constructora. Requiere por parámetros los dos elementos SELECTs del HTML, y los
//	dos INPUTs que interactuarán en la clase.
//***********************************
initialize: function(select1, select2, asignar, liberar){

// guarda el objeto implícito para dentro de las funciones
var self = this;

this.select1 = select1;
this.select2 = select2;
this.asignar = asignar;
this.liberar = liberar;

//generar el array con todos los options del select1
this.select1.getElements('option').each( function(option) {
self.options1.push({
'id' : option.get('value'),
'name' : option.get('html'),
'state' : true
});
});

//generar el array con todos los options del select2
this.select2.getElements('option').each( function(option) {
self.options2.push({
'id' : option.get('value'),
'name' : option.get('html'),
'state' : true
});
});

//crea el evento de asignar para el botón
this.asignar.addEvent ('click', function () {
var options_selected = self.select1.getElements('option').filter( function(option){
return option.get('selected');
});

options_selected.each ( function (option) {
self.moveOptionToSelect2(option);
});
self.updateSelect2();
});

//crea el evento de liberar para el botón
this.liberar.addEvent ('click', function () {
var options_selected = self.select2.getElements('option').filter( function(option){
return option.get('selected');
});

options_selected.each ( function (option) {
self.moveOptionToSelect1(option);
});
self.updateSelect1();
});

//crea el evento de asignar para el doble click en el option
this.select1.addEvent ('dblclick', function () {
self.asignar.fireEvent('click');
});

//crea el evento de asignar para el doble click en el option
this.select2.addEvent ('dblclick', function () {
self.liberar.fireEvent('click');
});

},

//***********************************
// MOVE OPTION TO SELECT2
//	Realiza el moviento de los items en las arrays internas, y elimina el OPTION del HTML
//***********************************
moveOptionToSelect2 : function( option ) {

// guarda el objeto implícito para dentro de las funciones
var self = this;

// calcula la posición donde se encuentra el option en el array de options del select original
var position;
this.options1.each( function(item, index) {
if (item.id == option.get('value')) {
position = index;
}
});

// hace el intercambio en los arrays
this.options2.push(this.options1[position]);
this.options1.remove(position);

// borra el option del select original
option.destroy();

},

//***********************************
// MOVE OPTION TO SELECT1
//	Realiza el moviento de los items en las arrays internas, y elimina el OPTION del HTML
//***********************************
moveOptionToSelect1 : function( option ) {

// guarda el objeto implícito para dentro de las funciones
var self = this;

// calcula la posición donde se encuentra el option en el array de options del select original
var position;
this.options2.each ( function(item, index) {
if (item.id == option.get('value')) {
position = index;
}
});

// hace el intercambio en los arrays
this.options1.push(this.options2[position]);
this.options2.remove(position);

// borra el option del select original
option.destroy();

},

//***********************************
// UPDATE SELECT1
//	Vacía el primer SELECT de todos los OPTIONs, y los vuelve a crear según el array interno.
//***********************************
updateSelect1 : function() {

// guarda el objeto implícito para dentro de las funciones
var self = this;

// borra los options del select de destino, y lo regera según el array
this.select1.empty();

this.options1.each ( function(item) {
if (item.state) {
op = new Element('option', {
'id': 'dominio-' + item.id,
'value': item.id,
'html': item.name
});
op.inject(self.select1);
}
});

},

//***********************************
// UPDATE TO SELECT2
//	Vacía el segundo SELECT de todos los OPTIONs, y los vuelve a crear según el array interno.
//***********************************
updateSelect2 : function() {

// guarda el objeto implícito para dentro de las funciones
var self = this;

// borra los options del select de destino, y lo regera según el array
this.select2.empty();

this.options2.each ( function(item) {
op = new Element('option', {
'id': 'dominio-'+item.id,
'value': item.id,
'html': item.name
});
op.inject(self.select2);
});

}
});

source

Avoid javascript errors in IE using console.log

function debug(what){
if(window.console && window.console.firebug){
console.log(what);
}
else{
alert(what);
}
}

function prueba(){
var algo = document.getElementById('test');
debug(algo);
}

source

JavaScript Hello Workd

<html>
<head>
<title>Titel der Webseite</title>
<!-- Evtl. weitere Kopfinformationen -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function doSomething(){
alert(document.getElementById("foo").value);
alert($("#foo").val());
}
</script>
</head>
<body onload="doSomething()">

Inhalt der Webseite
<input type="text" id="foo" />
<input type="button" name="Text 1" value="Text 1 anzeigen" onclick="doSomething()">
</body>
</html>

source

PNG Support – NO OTHER FILES NEEDED

<!--[if lt IE 7]>
<script language="JavaScript">
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
for(var i=0; i<document.images.length; i++)
{
var img = document.images[i]
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
{
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style="" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src='" + img.src + "', sizingMethod='scale');"></span>"
img.outerHTML = strNewHTML
i = i-1
}
}
}
}
window.attachEvent("onload", correctPNG);
</script>
<![endif]-->

source

Ntz Modal Box

var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
function modalBox(content, width, callback) {
if(!content){
$('#ntz_modal').remove();
$('#ntz_overlay').fadeOut(function(){$(this).remove();});
try{if(IE6){$('body').find('select').visibility('visible');}}catch(err){};
return false;
}
try{if(IE6){$('body').find('select').visibility('hidden');}}catch(err){};
$('body').append('<div id="ntz_overlay"></div>');
$('#ntz_overlay').css({
width			:		'100%',
height		:		$(document).height(),
position	:		'absolute',
left			:		0,
top				:		0,
backgroundColor	:	'#FFFFFF',
zIndex		:	9990,
opacity		:		0
}).fadeTo(200, 0.5);
$('body').append('<div id="ntz_modal"></div>');
$('#ntz_modal').css({
border		:		'1px solid #2d7abb',
width			:		width ? width : 350,
backgroundColor	:	'#FFFFFF',
position	:	'absolute',
left			:	'50%',
top				:	$(document).scrollTop(),
zIndex		:	9995,
marginLeft:	-(Math.ceil((width ? width : 800)/2))
}).append(content);
try{
callback.call();
}catch(err){};
$(document).bind('scroll', function(){
$('#ntz_modal').css({
top:$(document).scrollTop()
});
});
};

source

Snipplr Plain/Highlighted Text Greasemonkey Script

// ==UserScript==
// @name          Fix Snippet's Plain/Highlighted Text link
// @author        Andy Harrison
// @namespace     <a href="http://dragonzreef.com/greasemonkey/snipplr_plainhighlighted.user.js" >http://dragonzreef.com/greasemonkey/snipplr_plainhighlighted.user.js</a>
// @description   When viewing a snippet, fixes the Plain/Highligted Text link to go to the version you're looking at instead of the latest version.
// @include       <a href="http://snipplr.com/view" >http://snipplr.com/view</a>*
// ==/UserScript==

window.addEventListener("load", function()
{
var viewbar = document.getElementById("viewsource");
if(!viewbar) return;
var a = viewbar.getElementsByTagName("a");
for(var i=0; i<a.length; i++)
{
if(a[i].innerHTML == "Plain Text")
{
a[i].href += document.location.href.replace(/^http://snipplr.com/view/d+(.d+).*$|.*/,"$1");
return;
}
else if(a[i].innerHTML == "Highlighted Text")
{
var vers = document.location.href.replace(/^http://snipplr.com/view.php?([^#]*&)*?id=d+(.d+).*$|.*/,"$2");
a[i].href = a[i].href.replace(/^(http://snipplr.com/view/d+)(.*)$/, "$1"+vers+"$2");
return;
}
}
}, false);

source

come costruire un’estensione Plugin

/**
* sketch jQuery Plugin
*
*/
(function($){
$.fn.extend( {
mymethod: function(options){
var defaults = {};
var options = $.extend(defaults, options);
return this.each(function(){
var __e = $(this);
// todo
// default options in "options"
});
}
});
})(jQuery);

source