Shaikh Sonny Aman’s Blog

previously www.mailtoaman.com

JQuery custom attribute selector, extending JQuery

Posted on | April 15, 2008 |

Problem: In my current project, i had many links and divs which
performs some tasks as they are clicked. say, some are links in
the list which shows categories, clicking this links, i need to show
the items. Again, clicking each item, i need do some other tasks. In
this way, all the action links/divs can be categorized.

I need to tell jquery to perform something on click event of those.

Current Solution:

Use different class or id and get it like $(”#id”) etc.

Problem of this:

It will limit you to use id’s which can be conflicting with other settings.

What I am doing:

Extended JQuery :)

say I have the following links(there are many other comtypes):

<a comtype=’category’ comid=” ….
<a comtype=’category’ comid=” ….
<a comtype=’category’ comid=” ….

Now, Need to bind click event to all comtype=’category’

jQuery.extend(
    jQuery.expr[ ":" ],
    {
        catitem : (
        “jQuery( a ).attr( comtype) == ‘category’ “         
         )

    }
);

The code above will let me do the below:

$(‘a:catitem’).bind(’click’,function(){
    // do stuff   

});

Hope it may help you in such situations.

Comments

5 Responses to “JQuery custom attribute selector, extending JQuery”

  1. H2
    April 15th, 2008 @ 9:08 am

    you could do the same as show below

    $(”a[comtype='category']“).click(callback(){});

    should be more easier :)

  2. Shaikh Sonny Aman
    April 15th, 2008 @ 9:22 am

    Hasin bhai,surely in this case your solution would server perfect! thank you.

    Actually, my case was little more complex, sorry i did not mentioned the full story.

    I need to do add some other conditions also lik:
    “jQuery( a ).attr( comtype) == ‘category’ && jQuery( a ).attr( stock) > 0“ etc.

    Thank you again for your nice lesson.

  3. H2
    April 15th, 2008 @ 10:07 am

    in that case, here is the solution

    <a href="#" comtype=’abcd’ stock=’1′>Its 1</a><br/>
    <a href="#" comtype=’abcd’ stock=’2′>Its 2</a><br/>

    <a href="#" comtype=’abcd’ stock=’-2′>Its -2</a><br/>

    <input type="button" onclick="filterA();" value="filter"/>

    <script>
    function filterA()
    {
    alert("Hello");
    $("a[@comtype='abcd']").not($("a[@stock^='-']")).bind("click",function(e){alert(’hi’)});
    }
    </script>

  4. H2
    April 15th, 2008 @ 10:08 am

    but you are right, sometime its definitely useful to extend the expressions. heh heh

  5. Shaikh Sonny Aman
    April 15th, 2008 @ 8:41 pm

    WOW, great !! Hasin bhai, there is left a lot to know !!!
    Thank you very much again :D

Leave a Reply