$("document").ready(function() {
// The DOM is ready!
// The rest of the code goes here
});
$(function() {
// The DOM is ready!
// The rest of the code goes here
});
You might do it like this:
or this:
// IIFE - Immediately Invoked Function Expression
(function($, window, document) {
// The $ is now locally scoped
// Listen for the jQuery ready event on the document
$(function() {
// The DOM is ready!
});
// The rest of the code goes here!
}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
you might do it like this:
// sets an element's title attribute using it's current text
$(".container input#elem").attr("title", $(".container input#elem").text());
// sets an element's text color to red
$(".container input#elem").css("color", "red");
// makes the element fade out
$(".container input#elem").fadeOut();
// cache the live DOM element inside of a variable
var elem = $("#elem");
// sets an element's title attribute using it's current text
elem.attr("title", elem.text());
// sets an element's text color to red
elem.css("color", "red");
// makes the element fade out
elem.fadeOut();
// alternate way via chaining. P.S. It does looks messy.
elem
.attr("title", elem.text())
.css("color", "red")
.fadeOut();
you might do it like this:
$("#longlist li").on("mouseenter", function() {
$(this).text("Click me!");
});
$("#longlist li").on("click", function() {
$(this).text("Why did you click me?!");
});
$('.class').click(function(){
$(this).text("Why did you click me?!");
})
// cache the target element's parent first
var list = $("#longlist");
list.on("mouseenter", "li", function(){
$(this).text("Click me!");
});
list.on("click", "li", function() {
$(this).text("Why did you click me?!");
});
// delegate event via parent, like a boss.
You might do it like this:
$.ajax({
url: "getName.php",
type: "get",
data: {
foo: 'bar'
},
success: function(data) {
// updates the UI based the ajax result
$(".person-name").text(data.name);
}
});
function getName(personid) {
var dynamicData = {};
dynamicData["foo"] = 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);
});