jquery cheatsheet

http://test.ical.ly/2010/11/16/best-practices-for-jquery-development-my-link-collection-so-far/

Image Mouseover Hoover

    // Apply image hover
    $('#foo img').hover(  
      function() {
        $(this).attr('src', '/images/image-hover.png')
      },  
      function() {
        $(this).attr('src', '/images/image.png')
      }
    );   

 

Remove empty formfields on submit

        // remove empty form fields before submit
        $("form").submit(function()
        {
            $(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
            
            return true; // ensure form still submits
        });   

Enlarge click area

<script type="text/javascript">
  $('.link_container').click(function () {
    window.location = $(this).find('a').attr('href');
  });
</script>

Get current element type (tag type)

$(this).attr('tagName');

Wait for dom load

$(document).ready(function() {
  // Do something
});

Wait until the page is completely loaded (including graphics)

$(window).load(function() {
  // Do something
}); 

php str_replace equivalent

var result = subject.split(search).join(replace);

Widths

var border = $('elem').outerWidth() - $('elem').innerWidth();  var padding = $('elem').innerWidth() - $('elem').width();  var marging = $('elem').outerWidth(true) - $('elem').outerWidth();

Parse html code

var html = "<h1>Hello<h2";

// html text to dom
var doc = document.implementation.createHTMLDocument("");
doc.documentElement.innerHTML = evt.data['html']

$(doc).doSomeJQueryStuff();

// dom to html text
html = doc.documentElement.innerHTML;

 

Detect IE // Version

$(function() {

    if ($.browser.msie) {
      if ($.browser.version.substr(0,1) <= 7) {
        /* do something */
      }
    }

});

Timeout

setTimeout( function() {
   doSomething();
}, 500);

Load from CDN and fallback to local

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/jquery-3.2.1.min.js"><\/script>')</script>

 

Jquery in Joomla, Drupal & Co

Use the long syntax e.g. jQuery("#header").hide();