Search code examples
javascriptcsstextareahighlighting

How can I make this little javascript work with 2 textarea elements without killing the CSS?


The basics:

I'm styling a textarea with CSS, and using javascript to highlight the textarea when the user clicks inside.

This works fine with one textarea, but when I try to make more (by changing the javascript from .getElementById to .getElementsByClassName and updating the tags accordingly) I mess something up and lose all of the CSS.

How can I make this work with two textareas?

Cheers and thanks for your help!

.html page:

<textarea name="styled-textarea" id="styled" ; this.onfocus=null; setbg('#e5fff3')">All      this nice stuff goes inside here | http://www.website.com</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("styled");
    textBox.onfocus = function() {
    textBox.select();

    // Work around Chrome's little problem
    textBox.onmouseup = function() {
        // Prevent further mouseup intervention
        textBox.onmouseup = null;
        return false;
    };
};
</script>

All this nice stuff goes inside here.
<textarea name="styled-textarea" id="styled" ; this.onfocus=null; setbg('#e5fff3')">All     this nice stuff goes inside here | http://www.website.com</textarea>

CSS:

textarea#styled {
width: 60%;
font-size: 24px;
border: 3px solid #cccccc;
padding: 5px;
font-family:'Arial', sans-serif
}       

Solution

  • I tried to edit mrtsherman's answer, but my suggestion was rejected, so I'll just add a new answer. The code below fixes his.

    Switching from .getElementById to .getElementsByClassName requires three things:

    1. Changing id to class on both your textarea elements.
    2. Updating your CSS from textarea#styled to textarea.styled.
    3. Use .getElementsByClassName instead of .getElementById (note, it returns an array of elements, not one).

    Demo: http://jsfiddle.net/ThinkingStiff/WnJar/

    Script:

    var textBoxes = document.getElementsByClassName("styled");
    
    for (var i = 0; i < textBoxes.length; i++) {
    
        var textBox = textBoxes[i];
    
        textBox.onfocus = function() {
    
            this.select();
    
            // Work around Chrome's little problem
            this.onmouseup = function() {
    
                // Prevent further mouseup intervention
                this.onmouseup = null;
                return false;
    
            };
    
        };
    
    };