5 useful jquery snippets you should know now

Posted on Sep 24 2014 - 4:28pm by Eric Tompkins

5 jquery code snippets

Jquery is a very helpful lightweight library built on top of JavaScript. It is very useful for front-end development as one can perform a number of actions such as event handling, DOM manipulation, add HTML elements to the document or change values of the text fields etc. Here is a list of simple yet useful jquery snippets you must know to perform some common tasks.

1) Check if something is hidden using jQuery
Any element can be checked to see if it is hidden using jQuery, here is the snippet for that:

here element might be a class or an id assigned to the element to check and you may use hash (#) for ‘id’ selection while a dot (.) for class selection.

2) Check if a Checkbox is selected using jQuery

3) Enable or Disable Text input field using jQuery

4) Specific Event Handling Using jQuery
At times it is required to perform several actions based on some other actions for example you might want a user to input his name in an input text field using a dialog box before making an ajax call. What you need to do is to let the ajax code to wait until you give it a signal to execute after the user inputs his name. We use jQuery $.when() and $.then() methods for this task. These methods are dependent on deferred methods, here is a sample code that will help you understand better:

The above code says, wait for the executor to give a signal, then run the ‘then’ function accordingly after the executor is resolved. This is very useful in building applications and more specifically timing event handling.

5) Event Binding on Dynamically Created Elements
Suppose I have a div with id “wrap” and I append a button with id “coolButton” to this div using jQuery:

I also have a click event bound to this dynamically created button element such as:

The Solution:

For the click event to work on the dynamically created event, we will have to use .on() method instead such as:

About the Author

Eric Tompkins is an Experienced Web Developer and Digital Media Professional. As well as a Professional Photographer and Technical Instructor. You can follow on Twitter @_codemics.