Making HTML tags more useful by custom attributes

Being good is commendable, but only when it is combined with doing good is it useful.
-Anonymous


I have been over using a simple technique to pass on more data to an HTML element in order to manipulate it better using jQuery. What I do is, I add as many custom attributes to an element and later retrieve them like this

$(element).attr(customAttribute);

So if I wanted to show or hide particular div s on the click of a checkbox, I d first write the HTML like this:

<input type="checkbox" div2toggle="div1"  />
<input type="checkbox"div2toggle="div2" />
<input type="checkbox"div2toggle="div3" />
<input type="checkbox"div2toggle="div4" />
<div id="div1">Content for div 1</div>
<div id="div2">Content for div 2</div>
<div id="div3">Content for div 3</div>
<div id="div4">Content for div 4</div>

And then I d put the following inside $(document).ready(); or wherever

$(document).ready(function(){
    $(":checkbox").change(function(){
        $($(this).attr("div2toggle")).toggle();
    });
});

Using this technique will help you create tabbed content, non-form based input elements, auto hiding content on checkboxes or radio buttons and much more. Saves quite a bunch of lines of code!

Categories: jQuery, Tips | 2 comments

Comments (2)

  1. Thanks for showing me this tip dude. Digging your blog posts ;)

  2. Pingback: Toggle TinyMCE rich text editor effectively

Leave a Reply

Required fields are marked *

*