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 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.
Dom Ready
Ready
// 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 $(document).ready(function(){ // do something after DOM (page) is loaded });
Console Log
Console
// 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');
Empty
Check if Empty
// Check if an element is empty if ($('#tableinfo').is(':empty') ) { // do something } else{ // do other }
Element exists
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>'); };
Click
Click
// Active the click for the ID refresh $( "#refresh" ).click(function() { // do something });
Toggle
Toggle
// Switch on / off the visibility for the element specified (display:none) $("#loading").toggle();
Sleep
Sleep
// 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){ break; } } }
Format Date Time
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(" "); console.log(strDateTime); //Pad given value to the left with "0" function AddZero(num) { return (num >= 0 && num < 10) ? "0" + num : num + ""; }
Same Height
Resize same height
// Resize a div with the same height of another div $(divToResize).css('height',$(container).innerHeight())
Smooth Scroll
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 class and attribute
// Select all elements with class gmnoprint and with attribute title contains h2 $(".gmnoprint[title*='h2']" )
Select all except
Select all except
// Select all li except li with class name "active" $('li:not("li>.active")').hide();
Test if visible
Test if element is visible
// To test if an element is visible if($('#myid').css('display') == 'none'){ $('#myid').show('slow'); } else { $('#myid').hide('slow'); }
Select except
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')")
jquery wrap
Useful to use jQuery code in joomla where you must use jQuery because $ is not available
// Rename jQuery in $ for inside code (function($){ $("body").fadeOut(); })(jQuery);
Resize End
Resize End
This event is not a native javascript ot jQuery event. It's a workaround found on internet.
// RESIZE END
// http://www.sitepoint.com/jquery-capture-window-resize-event/ $(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); }); });
Height and Content
Adjust the height to the content
$("#bymanTextArea").height($("#bymanTextArea")[0].scrollHeight);
Highlight Input
Highlight all input fields based on its value.
$('.mainContent table td input').each(function(){ if ($(this).val() == '91.206.143.205') { $(this).css('background-color','#F8FD75'); } });
AJAX
AJAX
// Ajax var pWrong=$("#wrong").is(':checked') ? 1 : 0; var pVerbose=$("#verbose").is(':checked') ? 1 : 0; $.ajax({ type: "GET", url: "validateajax.php", data: {emails:strEmails, wrong:pWrong, verbose:pVerbose}, cache: false, dataType: "html", success: function(data) { $('#results').html(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
AJAX Parameters
// from a post of Stack Over Flow // Here is how POST data should be formatted: key1=value1&key2=value2&key3=value3 // 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
Static Var
function bymanReadmoreWithDelay(){ if(bymanReadmoreWithDelay.count == undefined){ bymanReadmoreWithDelay.count = 0; } else { bymanReadmoreWithDelay.count ++; } console.log( bymanReadmoreWithDelay.count) }
Loop Table, tr, td
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 ){ cVal=$(eTD).find("input").val(); // 1st Column if (iTD==0 ){ changeSource(iTR, eTR, cVal) }; // Apply some background color colorize(iTD, eTD, cVal); }); });
Loop li and add Image
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(document).ready(function(){ 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); }); });
Add link to images
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(document).ready(function(){ 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
To Be Continued...
Stay tuned, I will add more snippets soon...