Categories

jQuery Tips and Tricks

Posted on: July 11, 2015 by Dimitar Ivanov

A collection with jQuery examples of widely used performance tips, tricks and techniques that every javascript developer should know.

cache elements

For better performance you should reduce the DOM touches as much is possible. So it's a good idea to cache the jQuery objects. To cache an element just assign it into a variable for later use.

<script type="text/javascript">
var $element = $('#selector');
if ($element.is(':hidden')) {
    $element.addClass('active').show();
    $element.data("custom", "abc123");
}
//some other code
$element.hide();
</script>

check whether an element exists

Prior using a HTML element you need to ensure it's part of DOM.

<script type="text/javascript">
if ($("#selector").length) {
    //do something with element
}
</script>

how to find out if checkbox is checked

To test a jQuery object without modification use the .is() method. It returns boolean value.

<script type="text/javascript">
if ($('input').is(":checked")) {
    //input is checked
}
</script>

how to determine an element state

Basically you can use the .is() method to check element states as :visible, :hidden, :checked, :disabled, :selected.

<script type="text/javascript">
var is_hidden = $('.selector').is(":hidden");

var is_visible = $('.selector').is(":visible");
</script>

how to get value of checked element

To match all elements that are checked or selected use the :checked selector. It works for checkboxes, radio buttons and select elements. jQuery API says that for select elements only, use the :selected selector.

<script type="text/javascript">
//gets checked element
$('input[type="checkbox"]:checked');
//gets checked element value
$('input[type="radio"]:checked').val();
</script>

how to get selected option value

To select all elements that are selected use the :selected selector. It works only for option elements.

<script type="text/javascript">
$("select").find("option:selected").val();
//or even better
$("select option").filter(":selected").val();
</script>

how to detect ESC or ENTER

For better user expirience, often you need to listen for keyboard events like keydown, keypress and keyup. In this example is useful to attach this behavior to document object. Then just use the event data to determine which is the pressed key.

<script type="text/javascript">
$(document).on("keyup", function (e) {
    var code = e.keyCode || e.which;
    switch (code) {
        case 13:
            //Enter
            break;
        case 27:
            //Escape
            break;
    }
});
</script>

how to disable a form element

You can disable these HTML elements: button, input, select, textarea, optgroup, option, fieldset. Before jQuery 1.6 the .attr() method was used to handle the disabled property. As of jQuery 1.6, the .prop() method should be used.

<script type="text/javascript">
$("button").prop("disabled", true);
</script>

how to enable a form element

So, to enable disabled HTML element, just set it's disabled property to false. Hint: do not use the .removeProp() method to remove native properties such as disabled, checked or selected.

<script type="text/javascript">
$("button").prop("disabled", false);
</script>

check if plugin is loaded

Developers often puts their whole javascript in a single file who loads on each web-page, but loads external jQuery plugins only on pages where they actually needed. So far so good. In such a cases, before initialize the plugin you must check if it exists. If you miss this step the browser will throw a TypeError: undefined is not a function

<script type="text/javascript">
var validate = ($.fn.validate !== undefined);
if (validate) {
    $("form").validate();
}
</script>

how to get DOM element from jQuery object

To get native DOM elements from jQuery array-like object use the .get() method.

<script type="text/javascript">
$("#div").get(0);

$("#div")[0];
</script>
More JavaScript topics
Social sharing

If you have questions about jQuery best practices, please drop a comment below. Thanks for reading.


0 Comments

Comments are closed