@manhnguyenv

Welcome to my blog!

jQuery Practice

July 17, 2018 22:39

jQuery (edit)

https://oscarotero.com/jquery/

https://github.com/oscarotero/jquery-cheatsheet/

http://gregfranko.com/jquery-best-practices/

https://htmlcheatsheet.com/jquery/

Begin

$(document).ready(function() {
    // let's get up in heeya
});

Shorthand

$(function() {
    // let's get up in heeya
});

And

// HANDLE: $(function)
// Shortcut for document ready
if ( jQuery.isFunction( selector ) ) {
    return rootjQuery.ready( selector );
}

Tips and Tricks

// Fine in modern browsers, though Sizzle does begin "running"
$('#someDiv p.someClass').hide();
 
// Better for all browsers, and Sizzle never inits.
$('#someDiv').find('p.someClass').hide();

Tips and Tricks

var j = jQuery.noConflict();
// Now, instead of $, we use j. 
j('#someDiv').hide();
 
// The line below will reference some other library's $ function.
$('someDiv').style.display = 'none';

Tips and Tricks

(function($) {
    // Within this function, $ will always refer to jQuery
})(jQuery);

Tips and Tricks

jQuery(document).ready(function($) {
 // $ refers to jQuery
});
 
// $ is either undefined, or refers to some other library's function.

Better way

  // Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
      list = $("ul.people");

  $.each(localArr, function(index, value) {
      list.append("<li id=" + index + ">" + value + "</li>");
  });

Best way

  // Dynamically building an unordered list from an array
var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
list = $("ul.people"),
dynamicItems = "";
$.each(localArr, function(index, value) {
dynamicItems += "
<li id=" + index + ">" + value + "</li>";
});
list.append(dynamicItems);

AJAX

$.ajax({
    type: 'GET',
    url : 'path/to/json',
    data : yourData,
    dataType : 'json',
    success : function( results ) {
        console.log('success');
    })
});

Better AJAX

  function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    return $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData
    });
  }

  getName("2342342").done(function(data) {
    // Updates the UI based the ajax result
    $(".person-name").text(data.name); 
  });

Hover

$('#someElement').hover(function() {
  // the toggle() method can be used here, if applicable
});

Categories