user1374796
user1374796

Reputation: 1582

Hide certain characters in a div

I'm looking to hide all instances of certain characters contained in a simple div.
Basically what I'm after is that when the page loads certain characters (in this instance 's' and 'e') will fade out and leave spaces in the sentence where the characters would have been.
This is as far as I've got so far:
HTML:
<div id="test">hello this is a test this is a test</div>
jQuery:

$(document).ready(function(){
$('#test').html($('#test').html().replace("s"," "));
$('#test').html($('#test').html().replace("e"," "));
});​

Here's a working jsFiddle too: http://jsfiddle.net/6vjt3/
but all this is doing is hiding the first 's' and 'e' in the sentence, and not the rest.
Preferably what I'd like to happen is that the jQuery would detect these letters and slowly fade them to white, therefore leaving a space proportional to the letter, can't figure out how to do this at all though.
Any suggestions would be great!

Upvotes: 0

Views: 3365

Answers (3)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I tried to do as you mentioned about fading it out.. See DEMO http://jsfiddle.net/6vjt3/3/

Full Code:

$(document).ready(function(){
    var charToReplace = ['s', 'e'];
    $('#test').html(function (i, v) {
        var resultStr = '';
        for (var i = 0; i < v.length; i++ ) {
            var ch = v.charAt(i);

            if ($.inArray(ch, charToReplace) >= 0) {
               resultStr += '<span class="hideMe">' + ch + '</span>';  
            } else {
               resultStr += ch;
            }
        }

        return resultStr;
    }).find('.hideMe').fadeOut(1000, function () {
        $(this).css('opacity', 0).show();            
    });

    //lets bring it all back
    setTimeout(function () {
        $('#test').find('.hideMe').css('opacity', 1);
    }, 5000);
});

Use regEx with g (global) on replace.. See below,

$('#test').html($('#test').html().replace(/s/g," "));
$('#test').html($('#test').html().replace(/e/g," "));

DEMO: http://jsfiddle.net/6vjt3/1/

Upvotes: 1

antonjs
antonjs

Reputation: 14318

In case you need to go back to the original data later, I suggest this approach:

var $hiddenElement = $('<span>').addClass('hidden');

$('#test').html($('#test').html().replace(/s/g, $hiddenElement.text(s)));
$('#test').html($('#test').html().replace(/e/g, $hiddenElement.text(s)));

Your CSS

.hidden {
  display: none;
} 

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You need to wrap these characters in a SPAN then fade out the SPAN. Using replace will get rid of them instantly, but will never fade-out.

Upvotes: 1

Related Questions