you are here: codestackercodes [RSS] → tag jquery [RSS]

background animation

requires jquery.ui or jquery.color (https://github.com/jquery/jquery-color)

$.fn.backgroundAnimation : function(bgcolor, fgcolor, duration) {
	$(this).animate({ backgroundColor: bgcolor }, duration).css('color', fgcolor);
}

highlight an element

requires jquery.ui or jquery.color (https://github.com/jquery/jquery-color)

$.fn.highlight : function (highlightColor, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = duration || 2000;
    var originalBg = this.css("background-color");

    if (!originalBg || originalBg == highlightBg)
        originalBg = "#FFFFFF"; // default to white


    $(this).css("backgroundColor", highlightBg).animate({ backgroundColor: originalBg }, animateMs, null, function () { $(this).css("backgroundColor", originalBg);  });
}

center vertically element

$.fn.center = function (relation) {
    var center_in = (relation) ? $(relation) : $(window);
    
    this.css("position","absolute");
    this.css("top", ( center_in.height() - this.height() ) / 2+center_in.scrollTop() + "px");
    this.css("left", ( center_in.width() - this.width() ) / 2+center_in.scrollLeft() + "px");
    return this;
};

add to bookmarks using jquery

$("a#bookmark").click(function(){
   var bookmarkUrl = this.href;
   var bookmarkTitle = this.title;
	 
   if ($.browser.mozilla) // For Mozilla Firefox Bookmark

   { 
	window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,"");
   } 
   else if($.browser.msie || $.browser.webkit) // For IE Favorite

   { 
	window.external.AddFavorite( bookmarkUrl, bookmarkTitle); 
   }
   else if($.browser.opera ) // For Opera Browsers

   { 
	$(this).attr("href",bookmarkUrl);
	$(this).attr("title",bookmarkTitle);
	$(this).attr("rel","sidebar");
	$(this).click();
   } 
   else // for other browsers which does not support

   { 
        alert('Please hold CTRL+D and click the link to bookmark it in your browser.');
   }
   return false; 
});

detecting ie version with jquery

var IE = $.browser.msie, IEv = $.browser.version;

if (IE) { //could be improved

    var IE6 = parseInt(IEv) == 6,
        IE7 = parseInt(IEv) == 7, 
        IE8 = parseInt(IEv) == 8, 
        IE9 = parseInt(IEv) == 9;
}

//Usage:


if (IE) {
    //Do something for all IE versions

}
if (IE7) {
    //Do stuff just for IE7

}
if (IE7 || IE8) {
    //Do stuff just for IE7 or IE8

}
if (!IE6) {
    //Do something if not IE6

}

simple jquery table sort

requires jquery.sortElements.js (https://github.com/jamespadolsey/jQuery-Plugins/blob/master/sortElements/jquery.sortElements.js)

via http://stackoverflow.com/questions/3160277/jquery-table-sort

var table = $('table');

$('th').wrapInner('<span title="Sort this column"/>').each(function(){
     var th = $(this), thIndex = th.index(), inverse = false;
     th.click(function(){
         table.find('td').filter(function(){
             return $(this).index() === thIndex;
         }).sortElements(function(a, b){
             return $.text([a]) > $.text([b]) ?
                 inverse ? -1 : 1
                 : inverse ? 1 : -1;
         }, function(){
			return this.parentNode; 
         });
         inverse = !inverse;
     });
});

smooth scrolling

http://snipplr.com/view.php?codeview&id=53669

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"

  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

simple jquery scroll to top

$(document).ready(function() {
	$('.backtotop').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
	});
});

placeholder attribute for inputs in IE

require jquery and modernizer

if(!Modernizr.input.placeholder){
	$("input").each(function(){
		if($(this).val()=="" && $(this).attr("placeholder")!=""){
			$(this).val($(this).attr("placeholder"));
			$(this).focus(function(){
				if($(this).val()==$(this).attr("placeholder")) $(this).val("");
			});
			$(this).blur(function(){
				if($(this).val()=="") $(this).val($(this).attr("placeholder"));
			});
		}
	});
}

open all externals links in a new window

$('a[href*=http:]').each(function(){
        if (this.host != window.location.host) {
                $(this).attr('target', '_new');
        }
});

appending a custom stylesheet with jquery

$('head').append('<link rel="stylesheet" href="safari.css" type="text/css" />');

listening changes

var html = $('#events').html();
setInterval(function(){ if($('#events').html() != html){ tooltip(); html = $('#events').html() } }, 3000);

easiest tooltip ever

based on http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery version

<style>
	#tooltip {
		position:absolute;
		border:1px solid #333;
		background:#f7f5d1;
		padding:2px 5px;
		color:#333;
		display:none;
	}
</style>

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

<script type="text/javascript">
	$(document).ready(function(){			
	    xOffset = 10;
		yOffset = 20;				

		$("a.tooltip").hover(function(e){											  
			this.t = this.title;
			this.title = "";									  
			$("body").append("<p id='tooltip'>"+ this.t +"</p>");
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").fadeIn("fast");		
	    }, function(){
			this.title = this.t;
			$("#tooltip").remove();
	    });	

		$("a.tooltip").mousemove(function(e){
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
		});
	});
</script>

<a href="http://cssglobe.com" class="tooltip" title="Web Standards Magazine">Roll over for tooltip</a>

resize browser

$(document).ready(function(){

$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
	var newWindowHeight = $(window).height();
	$("#container").css("min-height", newWindowHeight );
}

});

basic jquery events

$('.box_1').bind('click', function(){
  alert("Clicked Box 1");
});

$('.box_2').click(function(){
  alert("Clicked Box 2");
});

$('.box_3').click(function(){
  $(this).css('background', '#8C0')
});

$('.box_4').bind('dblclick', function(){
  $(this).text('Double Clicked');
});

$('.box_5').mouseenter(function(){
  $(this).css('background', '#C60');
}).mouseleave(function(){
  $(this).css('background', '#06C')
})

$('.box_6').hover(function(){
  // In

  $(this).text('IN')
}, function(){
  // Out

  $(this).text('OUT')
})

smooth scrolling with jquery

// Smooth scrolling within page anchors

$('a[href*=#]').click(function() {
    
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        
        var $target = $(this.hash);
            
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            
        if ($target.length) {
              var targetOffset = $target.offset().top;
              $('html,body').animate({scrollTop: targetOffset}, 1000);
              return false;       
        }      
     }        
});

clean way to open a popup window

$('a.popup').live('click', function(){
	newwindow=window.open($(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
});

seletores do jquery

http://docs.jQuery.com/DOM/Traversing/Selectors

$('h1') // elementos h1

$('#meuID') // elementos com id "meuID"

$('.minhaClasse') // elementos definidos com a classe "minhaClasse"

$('[width]') // elementos que possuem o atributo width definido

$('[width=500]') // elementos que possuem o atributo width definido como 500

$('img[width=300]') // imagens que possuem largura = 300

$('img[src$=png]') // imagens com final png

$('a[href^=http://localhost]') // links que comecem com http://localhost

$('a[href$=pdf]') // links com final pdf

$('a[href*=www]') // links que contém www

$(':empty') // elementos vazio

$('div:empty') // elementos div vazios

$(':has(p)') // todos elementos que tenham um parágrafo

$('div:has(a)'); // elementos div que possuem link

$("p:contains('dinei')") // parágrafos que contém a palavra "dinei"

$("p:eq(0)") // seleciona o primeiro elemento p

back to top

<a href="#top" onclick="$('html, body').animate({scrollTop:0}, 'slow'); return false;">top</a>

hide/show dl list with jquery

		$(document).ready(function() {
			$('dd').toggle();
			$('dt').click(function() {$(this).next('dd').toggle('slideDown');});
		});
Displaying Code 1 - 20 of 31 in total