Search code examples
jquerypasswordsmasking

jQuery Text Masking


I'm trying to create a small snipped that would allow for text to be masked unless a link was hovered over it. Something like this:

<span class="mask">My Information</span>
<a href="#">View Info</a>

When the page loads, the page is displayed as follows:

<span class="masked">••••••••••••••</span>
<a href="#">View Info</a>

Essentially the bullets would take up as much space as the text that its replacing. Then when a user clicks the "View Info" link, the mask would revert back to the information.

<span class="mask">My Information</span>
<a href="#">View Info</a>

There will be multiple instances of this on one page.

Any ideas? I don't really know where to begin.. I was thinking about making a bunch of password fields but thought it would get messy..


Solution

  • far from perfect i'm sure!

    jsfiddle

    (function($) {
    
        $.fn.toggleMask = function() {
    
            this.each(function() {
                if ($(this).hasClass('masked')) {
                    $(this).text($(this).attr('origValue'));
                    $(this).removeClass('masked');
                    var link = $(this).next();
                    link.text(link.text().replace(/Show/,'Hide'));
                }
                else {
                    $(this).attr('origValue', $(this).text());
                    $(this).text(new Array($(this).text().length).join('•'));
                    $(this).addClass('masked');
                    var link = $(this).next();                
                    link.text(link.text().replace(/Hide/,'Show'));
                }
            });
    
        return this;
    };
    })(jQuery);
    
    $(function() {
        $('.mask').toggleMask();
        $('a').click(function() {
            $(this).prev().toggleMask();
            return false;
        });
    });