How to Create Custom Filters in Jquery

How to Create Custom Filters in jQuery
by Janeth Kent Date: 17-12-2013 jquery css resources tutorials tips plugins snippets webdev


If you are a web designer or a developer you frequently need a shortcut to collect elements for jQuery.

In this post, based on the book Instant jQuery Selectors, you’ll learn how to build a custom filter in jQuery.

So, we try to built a filter that ia able to print the length of the elements that have the placeholder attribute set, taking advantage of a previously created custom filter. In addition, to see all of the available options in action, we’ll create a second filter to collect all of the elements having a name with less than a given number of characters.

Well, we have to follow 4 steps:

Step 1

Create a file using a simple text editor, like Notepad++ and rename it as custom-filters.html.

Step 2

Then, we’ll create a simple form with the typical fields like “Name”, “Surname”... All these fields have the specification of the type (type attribute) and the name (name attribute), but few of them also have a placeholder set (placeholder attribute).

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Instant jQuery Selector How-to</title>
      <style>
         input,
         select,
         textarea
         {
            display: block;
         }
      </style>
      <!-- Script will be placed here... -->
   </head>
   <body>
      <form name="registration-form" id="registration-form" action="registration.php" method="post">
         <label>Name:</label>
         <input type="text" name="name" placeholder="Name" />
         <label>Surname:</label>
         <input type="text" name="surname" placeholder="Surname" />
         <label>Email:</label>
         <input type="email" name="email" placeholder="Email" />
         <label>Phone:</label>
         <input type="tel" name="phone-number" placeholder="Phone number" disabled="disabled" />
         <label>Privacy:</label>
         <input name="privacy" type="checkbox" checked="checked" />
         <label>Contact me:</label>
         <input name="contact-me" type="checkbox" />
         <label>Sex:</label>
         <select name="sex">
            <option selected="selected" value="m">Male</option>
            <option value="f">Female</option>
         </select>
         <input type="submit" value="Register" />
      </form>
   </body>
</html>

Step 3

Replace the comment we put in the HTML () with the following code:

 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $.expr[':'].placeholder = function(elem) {
        return $(elem).attr('placeholder') !== undefined;
    };
    $.expr[':'].nameLengthLessThan = 
    $.expr.createPseudo(function(filterParam) {
        var length = parseInt(filterParam);
        return function(elem, context, isXml) {
            return $(elem).attr('name') !== undefined && 
            $(elem).attr('name').length < length;
      }
    });
    $(document).ready(function() {
        console.log($(':placeholder').length);
        console.log($('input:nameLengthLessThan(5)').length);
    });
</script>

Step 4

Save the file and try to open it with whatever browser. Then, look at the console’s output.

How it works

At the very beginning of our Script, we’ve added a property, or more specifically a function called placeholder to the :  attribute that belongs to the jQuery’s expr attribute. : is a property containing jQuery’s native filters and you can use it to add your own at runtime.

Inside the function definition, we just have a single statement that checks if the current element has the placeholder attribute set, and if so, it returns true to keep the element.

As you can see from the example, a filter is a function that accepts as an argument the current DOM element to process and needs to return true to keep it in the collection, and false to discard it.

You should use this method for creating a filter when the following are true:

  • You’re interested only in the element to process itself
  • The filter doesn’t accept an argument
  • The context to which the selection is applied doesn’t matter

The second filter, nameLengthLessThan, is a bit more complicated and uses the method introduced starting from jQuery 1.8 by witch we pass an anonymous function to the create a pseudo function having a parameter that represents the argument passed to the filter when you use it.

Then, inside it, we create another function that will be returned and that is responsible for performing the filtering.

Finally, jQuery passes the element to be processed (elem parameter), the DOM Element or DOM Document from which selection will occur (context parameter), and a Boolean that tells if you’re operating on an XML document.

This filter needs this pattern because our filter needs to know the limit of characters the name attribute of the element must comply with.

In other words, we need to pass the number of characters the value of the name attribute must respect.

Inside the inner-most function, we write the code to test if the element should be kept or not. For our example, this means checking whether the name attribute is set and its length is not less than the given length (stored using a closure inside the length variable).

Now that we’ve created the filters, we need to use them. Inside the handler for the document.ready event, there are two statements. The first calls the placeholder filter without parameters and implicitly using the Universal selector. The second uses the nameLengthLessThan filter passing 5 as parameter and using the Element selector. Using the Element selector in the second call will result in a performance improvement. Running the code will result in the following being printed in the console:

4  1

 

 

original source: http://flippinawesome.org/

 
by Janeth Kent Date: 17-12-2013 jquery css resources tutorials tips plugins snippets webdev hits : 8299  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

How To Add Filter Effects to Images with CSS

To achieve interesting effects on your images, learn about the 'filter' and 'Backdrop-Filter' properties of CSS. CSS filters are a very attractive feature of CSS that allows you to apply certain…

How to watch deleted or private Youtube videos

Today we are going to talk about the technique which you permit to be able to recover videos from Youtube that was deleted, made private or simply blocked by Youtube…

How to ‘leave’ a WhatsApp group without actually leaving

If you want to leave a WhatsApp group but don't want the 'You left the group' message to be displayed, read this article. Some people love WhatsApp groups, and some people…

The 6 Essentials for Creating a Visually Appealing Web Design

Creating a website might seem like a simple thing. After all, what do you really need besides a good hosting provider and relevant content, right? Well, the reality is quite…

How to get notified when one of your WhatsApp contact is online

Privacy is one of the most important aspects among most users of the popular Facebook messaging application. So much so, that many settings have been included in WhatsApp itself to…

How to change font size and format in WhatsApp

Your WhatsApp messages can be much more original and fun by changing the font, size, or format. Here's how. WhatsApp is the leading messaging app for virtually everyone, with permission from…

WhatsApp: How to View Deleted Messages

Words are carried away by the wind, as long as they are not written on WhatsApp. Sending it was like getting a tattoo, something you'll always like, or yet it'll…

How to enable Chrome's new feature that blocks ads that consume your CPU, battery, and Internet connection

Google has announced that it will begin experimenting with a technology that they have been developing for months, in order to improve the battery consumption of our computers and the…

Introduction to BEM (Block Element Modifier)

Problems with naming CSS classes I think I might not be the only one with this experience: after finally grasping all the important concepts regarding CSS I wanted to start giving…

Protect yourself: know which apps have access to your location, microphone and camera

When you install an application on your smartphone, you decide what permissions you give it, but it's not always clear. We tell you how to know if those permissions are…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration