zch
zch

Reputation: 3060

Why is the scrollWidth of a valid text area undefined?

I have found many answers suggesting I use scrollWidth and scrollHeight to get the content width and height, respectively, of a text area. However, my code returns the scrollWidth as undefined. Any idea why this could be the case?

function changewidth(o) {
    if ($(o).val().length>8)
    {
            var current = $(o).css("width");
            console.log($(".name").scrollWidth+'px');
        $(o).css("width",$(".name").scrollWidth+'px');
    }
}

And this javascript function is being called by this text area:

<textarea rows="1" onkeyup="changewidth(this)" class="name" type="textarea" placeholder="name"></textarea>

The console prints undefinedpx. Based on research, I have tried to alter the CSS and currently have the following:

.name {
    width: 100px;
    margin: 0;
    padding: 0;
    border: none;
    font-size: 20px;
    color: #00B45E;
    resize: none;
    overflow: hidden; 
}

Upvotes: 2

Views: 2173

Answers (2)

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You have to try this, No need to wrap currently passed object into $() unless you need it.

function changewidth(o) {
    if ($(o).val().length > 8) {
        var current = $(o).css("width");
        console.log(o.scrollWidth + 'px'); // o.scrollWidth
        $(o).css("width", o.scrollWidth + 'px'); // use object as o direclty
    }
}

With pure Javascript

function changewidth(o) {
    if (o.value.length>8)
    {
            var current = o.style.width;
            console.log(o.scrollWidth+'px');
            o.style.width = o.scrollWidth+'px';
    }
}

Fiddle

With pure javascript

Demo

Upvotes: 1

Rene Padillo
Rene Padillo

Reputation: 2358

scrollWidth only applies to plain Javascript, it seems you are using it on jQuery.

instead of $(".name").scrollWidth try changing it to document.getElementsByClassName("name").scrollWidth

Upvotes: 0

Related Questions