13 Trucos para jQuery

13 Trucos para jQueryLa siguiente es una recopilación de códigos básicos que he usado en algunos proyectos y otros más que agregué como complemento.

Cargar jQuery

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

Mostrar texto en el cuedro de búsqueda

Formulario

<form action="#" method="post">
<input id="SearchText" name="text" />
<button>Search</button>
</form>

Javascript

function populateElement(selector, defvalue) {
$(selector).each(function() {
if($.trim(this.value) == "") {
this.value = defvalue;
}
});
$(selector).focus(function() {
if(this.value == defvalue) {
this.value = "";
}

Buscar texto con jQuery

$.fn.egrep = function(pat) {
var out = [];
var textNodes = function(n) {
if (n.nodeType == Node.TEXT_NODE) {
var t = typeof pat == 'string' ?
n.nodeValue.indexOf(pat) != -1 :
pat.test(n.nodeValue);
if (t) {
out.push(n.parentNode);
}
}
else {
$.each(n.childNodes, function(a, b) {
textNodes(b);
});
}
};
this.each(function() {
textNodes(this);
});
return out;
};

Abrir enlace en una ventana nueva

$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
/*

Uso:

<a href="http://www.lepinskidesign.com.br/" rel="external">lepinskidesign.com.br</a>

Precargar imágenes

jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments[i]);
}
};
// Uso
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");
});
$(selector).blur(function() {
if($.trim(this.value) == "") {
this.value = defvalue;
}
});
}
populateElement('#SearchText', 'Escriba su búsqueda aquí..');

Mostrar contenido sólo para Internet Explorer

if ($.browser.msie) {
// Internet Explorer.
}

Expandir filas de una tabla

Para hacer que las filas (rows) de una tabla se expandan al hacer clic sonbre estas se requiere:

  1. Poner una clase (class) padre en cada fila (tr).
  2. Darke a cara fila padre (rd) un ID:.
  3. Dar a cada fila hoja una clase child.ID donde ID es el ID de la fila padre a la que pertnece.

Y por último, agregamos el siguiente Javascript

$(function() {
$('tr.parent')
.css("cursor","pointer")
.attr("title","Click to expand/collapse")
.click(function(){
$(this).siblings('.child-'+this.id).toggle();
});
$('tr[@class^=child-]').hide().children('td');
});

Revisar si un existe un elemento

if ($("#someDiv").length) {
//hooray!!! Existe...
}

Revisar si algo está oculto

if($(element).is(":visible") == "true") {
//Elemento visible
}

Deshabilitar el menú contextual

$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});

Obtener las cordenadas XY del puntero del mouse

$().mousemove(function(e){
//display the x and y axis values  inside the P element
$('p').html("X Axis : " + e.pageX + " | Y  Axis " + e.pageY);
});

Detectar el navegador

//A. Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. IE6 o suerior
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. IE6 o inferior
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//D. Firefox 2 o inferior
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );

Remover una palabra en un texto

var el = $('#id');
el.html(el.html().replace(/word/ig, ""));

Sobre esta entra

Para esta entrada se usaron códigos Javascript que he recopilado y otros extraidos de: www.tvidesign.co.uk, docs.jquery.com, www.javascripttoolbox.com, www.myinkblog.co, johannburkard.de y viralpatel.net.

Por Diego Cambiaso

Comunicador Social, Desarrollador de Software y UX Designer. Blogger desde el 2006, creador de Pixelco Tech. Viajero y fotógrafo. Entusiasta del diseño, apasionado por la tecnología y el social media. EN-ES-IT