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
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());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With