4 ms·
Nice tips. I definitely did not know about the data() method previously. On a related issue, does anyone have a nice way for passing "arguments" to a jquery fu
by jsdalton 18y ago
Nice tips. I definitely did not know about the data() method previously.
On a related issue, does anyone have a nice way for passing "arguments" to a jquery function from the html, while still using jquery selectors (i.e. not calling the function from an inline event handler)?
I whipped up a truncate function not too long ago that truncates a block of text to a certain word count and adds a "more" link to reveal the whole thing. I wanted to add a feature where I could specify from the HTML what word count the block should be truncated through. I ended up using the class...e.g. <div class="truncate 30">...</div> would truncate the text in the block to 30 words.
Just curious, in the spirit of this article, if anyone had any alternative approaches or better suggestions.
- geuis 18y agoYou can assign a custom attribute to your element, then select on that. So if you have an input where you want to store 200 characters but truncate at thirty, you could do input type="text" show="30" size="200" in jquery, it might be $('input[show]').attr(show)) to select that value. The input[show] would only select elements with the show attribute. If you only want to select inputs with certain show values, you could do input[show="30"] or input[show="10"] if your show values were 30 or 10.
- jsdalton 18y agoI shied away from that only because I wasn't sure about adding custom attributes and making my xhtml invalid, e.g. to a div block which doesn't have a show attribute in the spec. Getting the argument itself is actually easy enough, I more ended up struggling to find an "appropriate" or natural interface for it within the html itself.
- tr4nslator 18y agoCheck out the jQuery Metadata plugin: http://plugins.jquery.com/project/metadata http://plugins.jquery.com/project/metadata It lets you choose where to define this kind of custom data: in an arbitrary attribute, as a class within the className attribute, or in a script tag.