Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background-color of first word in textbox?

I have an text box input in my HTML. I know how to set the background color of the whole thing with CSS (background-color) but is it possible to only set the background-color of the first word? I want it so that if someone types in, for example, "hello there", the background color of the word 'hello' will turn orange, but if they type in "how are you", the word 'how' will turn blue.

I have gotten it to style the whole textbox in this JSFiddle here with jQuery and CSS, but is it possible to make it only set the background color of the first word?

like image 420
thatoddmailbox Avatar asked Mar 01 '15 18:03

thatoddmailbox


1 Answers

Quick solution (not perfect) writen in few minutes, but maybe it help You to create better solution.

http://jsfiddle.net/ea7qbdLx/8/

HTML:

<div class="magic-input-container">
    <div class="form-control first-word"></div>
    <input type="text" id="textbox" class="form-control" placeholder="Type here..."/>
</div>

JS:

$(document).on('keydown keyup change', '.magic-input-container input', function (){

    if(($(this).val().length) && ($(this).val().split(' ').length)){

        $(this).closest('.magic-input-container').find('.first-word').html($(this).val().split(' ')[0]).show();
    }
    else{

        $(this).closest('.magic-input-container').find('.first-word').hide();
    }    
});


$(document).on('click', '.magic-input-container .first-word', function (){

    $(this).closest('.magic-input-container').find('input').focus();
});

CSS:

body {
    padding: 10px;
}

.magic-input-container {
    width: 100%;
    height: auto;
    position: relative;
    float: left;
}

.magic-input-container .first-word {
    background: red;
    width: auto;
    height: 20px;
    line-height: 20px;
    box-shadow: none;
    margin: 6px 12px;
    padding: 0px 1px;
    border: 0px;
    top: 0px;
    position: absolute;
    border-radius: 0px;
    display: none;
    color: #FFF;
}
like image 176
Mateusz Mania Avatar answered Sep 20 '22 16:09

Mateusz Mania