dilettante
dilettante

Reputation: 381

Setting default html of div to be modified by keyup() event

I have a textarea whose value I want to duplicate into another div as a preview. It works fine, except that keyup seems to automatically clear the div to which it will be writing. Is there any way to prevent this? It's a usability concern not to have the default text appear in my output div.

$('.preview-wrap').html('<textarea maxlength="118" class="tweet" placeholder="My default"></textarea>');

$(".tweet").keyup(function (event) {
    var value = $(this).val();
    $('.tweet-preview').text(value);

 }).keyup();

See this fiddle for full example-- the "Output" area should include the "My default" text as indicated.

DEMO

Thanks!

Upvotes: 0

Views: 90

Answers (2)

NiiL
NiiL

Reputation: 2827

we can do this by JQuery - CSS trick, change your code with this.


HTML:

<div class="tweet-preview" placeholder="My Placeholder String" 
style="border:1px solid #666; min-height: 30px;" >My default</div>


JQuery:

$('.tweet-preview').attr("placeholder", $('.tweet').attr('placeholder'));


CSS:

[class=tweet-preview]:empty:not(:focus):before{
    content:attr(placeholder);
    color: #b3b3b3;
}

So we are creating FAKE PLACEHOLDER for your div.

Full Working DEMO

Upvotes: 0

Rakesh Kumar
Rakesh Kumar

Reputation: 2853

Here is the update code

$(".tweet").keyup(function (event) {
    var value = $(this).val();
    $('.tweet-preview').text(value);
    //console.log($('.tweet-preview').text() == '')
    if( $('.tweet-preview').text() === '' ){
        $('.tweet-preview').text("My Default")
    }
});

Demo

Upvotes: 1

Related Questions