jQuery tips and tricks
1. Determine the size of our document
In details, it’s a query of the DOM elements number, which the page contains. In jQuery this information is available in the following manner:
alert($('*').length);
2. Checking if a checkbox is checked
It’s simple – can be done in such a way:
if ($("#myCheckBoxID").is(':checked')) {
...
}
or by checking an attribute:
if ($('#myCheckBoxID').attr('checked')) {
...
}
3. Checking whether an element exists
if ($("#myElementID").length == 0)
alert('#myElementID does not exist');
else
alert('#myElementID exist!');
4. Checking if an element is visible
Is visible:
$("#myElementID").is(":visible");
Is hidden:
$('#myElementID').is(':hidden')
5. Finding an element by attribute
Going one step further, we can search for an item by attribute, even our own.
var p_id = 12345;
$('#container').find('div[data-photoid="' + p_id + '"]').hide();
This code is looking for a specific item (here: div), wherein the attribute data-photoid has a value of the specified variable (p_id), and hides the item if was found.
6. “Sticking” actions to the HTML elements
HTML
<span id="prev">PREV</span> 1 2 3 4 5 <span id="next">NEXT</span>
JS
$('#next').unbind();
$('#prev').unbind();
$('#next').click(function() {
clickTime = new Date().getTime();
alert(clickTime);
return false;
});
$('#prev').click(function() {
clickTime = new Date().getTime();
alert(clickTime);
return false;
});
n this example, the time of click is displayed (timestamp).
Next tricks in jQuery are not directly related to the document element.
7. Blocking the right mouse button in jQuery
$(document).bind("contextmenu", function(e) {
return false;
});
8. Short version of document.ready
For the document.ready event
$(document).ready(function() {
....
});
we can use shorter version:
$(function() {
...
});
