Live Character Count in jQuery Example

No Comment - Post a comment

This simple jQuery example will show you how to set up 'live' character count and how to display results as paragraph tooltip.

First, we need simple HTML file.

livetest.html

<html>
<head>
<script src="jquery-1.4.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
p {
border: 1px solid;
padding: 2px 10px 2px 10px;
}
</style>
</head>
<body>
<p>Europe, Germany, Berlin</p>
<p>Europe, Great Britain, London</p>
<p>America, New York</p>
</body>
</html>


I don't want to complicate my life with external css file, because I only need two attributes, border and padding to visually display different paragraphs.

Now, let's see how we can set 'live' character count on paragraphs.


$('p').live('mouseover', function() {

// calculate number of characters in paragraph
var chnum = $(this).text().length;

// show it as tooltip
$(this).attr('title', chnum+' characters in this paragraph.');

});


You can see I don't use bind() jQuery function, but instead I use live. Main difference is that live() will attach our mouseover event to every paragraph created in the future, not only existing ones like bind() will do.

I wanna show you this important difference, so I'll attach click event to paragraph which will append new paragraph with random number of characters after clicked one. Here is entire file.

script.js

$('p').live('mouseover', function() {

// calculate number of characters in paragraph
var chnum = $(this).text().length;

// show it as tooltip
$(this).attr('title', chnum+' characters in this paragraph.');

});

$('p').live('click', function() {

// create random string with max length 40
var rn = Math.floor( Math.random()*40 );
var rs = '';
for(i=0; i<rn; i++) {
rs += Math.floor( Math.random()*9 );
};

// create new paragaph and append it
$('<p> - new paragraph added '+rs+'</p>').appendTo($(this));
});


Hope this will be useful to someone.

This Post has No Comment Add your own!

Post a Comment