views:

55

answers:

2

How would i be able to select a word and change the colour of that one word?

e.g. add a span with style and chage the font colour.

Can someone lead me down the right path please.

Jquery

 function edit_addon (div_id) {    
    $("#"+div_id).attr ('contentEditable', true)
             .css ('color','#F00') 
             .css ('cursor','Text') 
             ; 

 } 

HTML

 <div id="34" ondblclick="javascript:edit_addon(34)">Editable Text</div>

Thank you,

+1  A: 

This should work for you. In general it is a lot easier to give your elements a class and then in your ready function (Seen here in short hand.) you can set up any dynamic aspects of the page.

<style type="text/css">
    .Word { color:#F00;cursor:text;padding:20px; }
</style>
<script type="text/javascript">
    $(function () {
        $("div.Editable").each(function () {
            var elem = $(this),
                text = elem.text(),
                words = text.split(" "),
                innerHtml = "<span>" + words.join("</span>&nbsp;<span>") + "</span>";
            elem.html(innerHtml);
        });
        $("div.Editable span").live("dblclick", function (evt) {
            $(this)
            .attr({ contentEditable: true })
            .addClass("Word");
        }).live("mouseout", function () {
            var elem = $(this);

            elem
            .attr({ contentEditable: false })
            .removeClass("Word");

            var text = elem.text(),
                words = text.split(" "),
                innerHtml = "<span>" + words.join("</span>&nbsp;<span>") + "</span>";

            elem.replaceWith($(innerHtml));
        });
    });
</script>

<div id="Editable34" class="Editable">
    Editable Editable Editable
</div>
ChaosPandion
The only issue with this is when there are multiple words in one `div`, the entire thing will become editable.
SimpleCoder
@SimpleCoder - My reading comprehension fails me again, let me fix that.
ChaosPandion
@SimpleCoder - I am not 100% happy with this but I can't be doing the OPs job now can I?
ChaosPandion
+4  A: 

The easiest way would be to dynamically add spans with the individual in the div and just change the color of the current span. Here's the basic idea:

$(".Editable").dblclick( function () {
    var words = $(this).text().split(" ");
    var result = "";
    for (var i=0; i<words.length; i++) {
        result.append("<span class='word'>" + words[i] + "</span>");
    }
    $(this).innerHTML = result;
}

#CSS

span.word:hover { color: #0f0; }
CrazyJugglerDrummer
You should probably avoid `for...in` on arrays. `for...in` is intended to iterate over object properties, so if the array prototype has been modified those property names would be included in the result.
Andy E
@Andy E, thanks, I'm doing too much mental switching between languages. edited :)
CrazyJugglerDrummer