views:

236

answers:

2

I have piece of javascript code, which should process when the browser window is resized.

resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px'

Tryed this stuff (doesn't work):

window.onresize = function(event) {
resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px'
}

Full code available - http://jsbin.com/adelu3/2/ (see page source)

Html (generated by the script):

<div class="resizable-textarea">
    <span>
        <textarea class="resizable processed" cols="" rows=""></textarea>
        <div class="resize"></div>
    </span>
</div>

Thanks.

+1  A: 
$(this)[0].offsetWidth

offsetWidth is a property of elements. In the callback code of window.onresize, this is a Window, which doesn't have an offsetWidth.

What is this supposed to be? (The onresize event is not present in the linked code.) If you want to read the window width, use $(window).width().

If you want to read the width of some other (ancestor?) element that you had as this in the enclosing scope, you must either find that element by looking up from the resize element, or retain a reference to the other element in a closure, eg.:

var that= this;
$(window).resize(function() {
    resize.style.marginRight= resize.offsetWidth-that.offsetWidth+'px'
});

(nb. $(this)[0] does precisely nothing.)

bobince
Sorry, I don't have enough knowlegde in javascript. Can you give a full code?
Happy
This doesn't work - $(window).width(function() {resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px')});
Happy
And this too - $(window).width(resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px');
Happy
Thanks. It doesn't work everytime, sometimes gives a negative margin.
Happy
So, here is a html: <div class="resizable-textarea"><span><textarea class="resizable processed" cols="" rows=""></textarea><div class="resize"></div></span></div>
Happy
Function changes Margin-right for div.resize. Its >better< to change Width instead. It could take the Width from textarea.resizable and give it to div.resize
Happy
OK, so you could use `$(resize).closest('div').width()` to get the width of the `resizable-textarea` element from the textarea, if that's what you want. Or store a reference to it in `that`, as above. `this` is a special variable that corresponds to the object a function was called on, so you can't get the outer function's `this` from the nested function directly.
bobince
A: 

Made myself.

This is a mixed solution, it shares @bobince's code and my own.

var tarea= this;
function resize_width(){ resize.style.width= tarea.offsetWidth+'px'}
resize_width();
$(window).resize(function() {resize_width()});
Happy