Categoria: Javascript
Visite: 11798
Stella inattivaStella inattivaStella inattivaStella inattivaStella inattiva

This page contains some jquery code snippets. I wrote them day by day during developping, so they are not well organized but for sure they are useful.




 //  This is the onload for jQuery...for javascirpt we need to write the function inside the body tag <body onload="initialize()">
// jquery does not need to do it. 
// Another important difference is:  with pure javascript you can have only one onload function, with jquery  more than one.
// Here what you need in jquery in alternative to onload. 
// Last note: do not use onload when you use the ready function of jquery

  // do something after DOM (page) is loaded




// this is pure Javascript and it is useful for debug your javascript code in place of alert()
console.log('what you want to write to the browser console');



Check if Empty

// Check if an element is empty
if ($('#tableinfo').is(':empty') ) {
  // do something
 } else{
  // do other



Check if an Element exists

// add a Mini Menu only if it not exists
if (! jQuery('#bymanMenuMobile').length) {
      jQuery("body").append('<div id="bymanMenuMobile" class="bymanMenuMini"><i class="icon-menu-3"></i></div>');




// Active the click for the ID refresh
$( "#refresh" ).click(function() {
// do something




// Switch on / off the visibility for the element specified (display:none)




// Simple Function in pure javascript to simulate a sleep function - it will be freeze the browser
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
      if ((new Date().getTime() - start) > milliseconds){



Datetime formatted

// Prepare the Current Date Time, format it and print it in the console
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");


//Pad given value to the left with "0"
function AddZero(num) {
  return (num >= 0 && num < 10) ? "0" + num : num + "";



Resize same height

// Resize a div with the same height of another div



Scroll Top

// Scroll to a top of specific element, in the example clicking on ID logo
// Click on Open Info Table
$( "#logo" ).click(function() {
   if ($('#map_canvas').length) {
   $("#map_canvas").css('height',window.innerHeight - 20).animate(700); // 45 to leave the footer
   $('html, body').animate({scrollTop: jQuery("#map_canvas").offset().top}, 700); 



Select class and attribute

// Select all elements with class gmnoprint and with attribute title contains h2
$(".gmnoprint[title*='h2']" )



 Select all except

// Select all li except li with class name "active"


Test if element is visible

// To test if an element is visible
if($('#myid').css('display') == 'none'){ 
 } else { 



Select and Exclude

// Select Elements and Esclude the class .button
$(".content_box a").not(".button")

// Alternatively, you can also use the :not() selector:
$(".content_box a:not('.button')")



Useful to use jQuery code in joomla where you must use jQuery because $ is not available

// Rename jQuery in $ for inside code



Resize End

This event is not a native javascript ot jQuery event. It's a workaround found on internet.

// $(window).bind('resize', function(e) { window.resizeEvt; $(window).resize(function() { clearTimeout(window.resizeEvt); window.resizeEvt = setTimeout(function() { // my code after window is resized is finish console.log("Resize End: " + $(window).width() + "x" + $(window).height()); }, 250); }); });


Adjust the height to the content



Highlight all input fields based on its value.

$('.mainContent table td input').each(function(){
	if ($(this).val() == '') {




// Ajax
var pWrong=$("#wrong").is(':checked') ? 1 : 0;
var pVerbose=$("#verbose").is(':checked') ? 1 : 0;
	type: "GET", 
	url: "validateajax.php",            
	data: {emails:strEmails, wrong:pWrong, verbose:pVerbose},
	cache: false,
	dataType: "html",            
	success:	function(data) {    
			$('html, body').animate({scrollTop: $("#results").parent('div').offset().top - 4}, 800);			
	error:		function (request, status, error) {
		// request.responseText contains the page error
  	$('#myMessages').html('<p style="color:red">' + status + ": " + error + "</p>")



AJAX Parameters

// from a post of Stack Over Flow
// Here is how POST data should be formatted:

// Example (note the & as a separator):
'code=' + code + '&userid=' + userid

// But jQuery does that for you if you specify your data as an object:
data: { code: code, userid: userid }



Static Var

function bymanReadmoreWithDelay(){
    if(bymanReadmoreWithDelay.count == undefined){
          bymanReadmoreWithDelay.count = 0;
       } else {
         bymanReadmoreWithDelay.count ++;
      console.log( bymanReadmoreWithDelay.count)


Loop all Table TRs and TDs

// Loop all TR
$('.mainContent table tr').each(function (iTR, eTR) {		
	// Loop all TD
	$.each(this.cells, function(iTD,eTD ){
		// 1st Column
		if (iTD==0 ){ changeSource(iTR, eTR, cVal) };
		// Apply some background color
		colorize(iTD, eTD, cVal);



Loop all li tag and add a link to Image

This code was used in a joomla site for the weblink component. I get the link from the text url and add it in the image.

// byman - Add link to image of weblinks
	jQuery('.links-my-sites li').each(function (iTR, eTR) {   
		var myURL=jQuery(this).find('a').attr('href');
		var myIMG=jQuery(this).find('p img');
		jQuery(myIMG).wrap(jQuery('<a>',{href:myURL, 'target':'_blank'}));
		console.log(myURL, myIMG);



Read the url address from the a tag and add  link to images

This script select all li tags under the class .links-my-sites and for each li select url and image and wrap the link in the images.

I used this script in this joomla website: myLinks->MySites

The page is category list of the component WebLink. The images are without link...

		jQuery('.links-my-sites li').each(function (iTR, eTR) {   
			  var myURL=jQuery(this).find('a').attr('href');
			  var myIMG=jQuery(this).find('p img');
			  jQuery(myIMG).wrap(jQuery('<a>',{href:myURL, 'target':'_blank'}));		  



To Be Continued... 

Stay tuned, I will add more snippets soon...