Reputation: 615
Since I'm not good enough in scripting I can't find right syntax.
Please take a look at Following image. I need to set div.dependable
's width
as X + 16px
, even while window resizing.
I have pretty similar example, please see code of http://demuri.lv
. Try to resize window there — blue block will be always in the horizontal and vertical center. But I can't figure out the correct coding for that.
jQuery, Modernizr loaded.
Upvotes: 0
Views: 946
Reputation: 169
You'll have to tap into the window resize event and be sure to use in your doc.ready loop
$(document).ready(function(){
$(window).resize(function() {
var x = ($(window).width() - $('div#mainwrap').width())/2;
var targ_w = (x+16) + "px";
$('div.dependable').css({'width': targ_w});
});
});
Upvotes: 1
Reputation: 5840
You will have first to hook on the resize
event of window
, find out the offset
of your wrapper from the left side and then modify the width
of your element accordingly, like so:
$(window).on('resize', function (){
var leftOffset = $('#main-wrap').offset().left;
$('.dependable').css('width', leftOffset + 16);
});
This will work as you asked, but I'd also suggest that you add the same statement in the first place so you get the correct width at $(document).ready
.
jQuery(document).ready(function ($){
var leftOffset = $('#main-wrap').offset().left;
$('.dependable').css('width', leftOffset + 16);
});
In order to stick with the principle of DRY code you might want to wrap the code up in a function statement; that would be highly suggested. Perhaps like so:
function offsetPlusX(targetElement, x){
var leftOffset = $('#main-wrap').offset().left;
targetElement.css('width', leftOffset + x);
}
Upvotes: 0
Reputation: 166
If I understand it correctly, this implies that X is the value of the window width - the #main-wrap width and then divide that by 2 to get the width of each side. You must make sure to call this function when the DOM is loaded and every time the window is resized.
jQuery(document).ready(function($){
calcDependable();
});
$(window).resize(calcDependable);
function calcDependable(){
var x = ($(window).width() - $("#main-wrap").width())/2;
x = (x < 0 ) ? 0 : x; // make sure value is always 0 or above
$(".dependable").width(x+16);
}
Upvotes: 0