Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML, jQuery: Bind width of one element to another

Tags:

html

jquery

I'd like to bind the width of a first element (foo) to the width of a second element (bar). I would want element "foo" to have its width change automatically when the width of element "bar" is changed.

I know I can set the width of element "foo" to the width of element "bar" as we can see in the code below, but this is a one-time thing. What happens if the width of element "bar" changes somewhere in the processing of the page after this code is executed? e.g. "bar" is a select element and its width changes as a result of an AJAX call - how would element "foo" get its width changed?

$('#foo').width($('#bar').width());

Thanks

like image 821
Ed Sinek Avatar asked Jun 28 '11 18:06

Ed Sinek


1 Answers

Resize events are bound only to the window and not to elements like divs, full discussion here: jQuery resize not working at FireFox, Chrome and Safari

The only solution would be to have a global variable and use it to update when bar size is changed. foo's width is set to the global variable. Add code in the method or code block that updates bar size, to update the global variable or the foo size directly using $(foo).width($bar.width());

function setBarHeight(value) {
   $('#bar').attr('width') = Number(value);
   $('#foo').attr('width') =  $('#bar').attr('width');
}

EDIT: This jQuery approach below doesn't work, updated answer above this line.

Add jquery handler for resize

$(document).ready(function() {
    $('#bar').resize(function() {
        $('#foo').width($('#bar').width());
    });
});
like image 66
Satish Avatar answered Sep 30 '22 12:09

Satish