Reputation: 47
This code works perfectly as I expected but the problem is when I refresh the page the t_con stays in absolute which should be fixed and when I resize the window less than 980px it is in absolute like what I need and if I resize again more than 980px it goes fixed.
I need it to stay fixed from start. I don't know why it is in absolute at first.
HTML CODE
<div id="t_con">
<div id="t">
</div>
</div>
CSS CODE
#t_con {
width: 100%;
position: absolute;
top: 0;
}
#t {
margin: 0px auto 0 auto;
background-color: #976398;
width: 980px;
height: 30px;
}
Javascript CODE
window.onresize = function(){
var header = document.getElementById('t');
var window_width = document.body.offsetWidth;
if(window_width < 980) {
header.style.position = "absolute";
} else {
header.style.position = "fixed";
}
}
Can anyone tell what am I doing wrong in here? And I don't want to use jQuery for this. So please do not suggest it. The reason I don't like jQuery is it already takes 90kb plus the code we are trying to execute.
Upvotes: 0
Views: 62
Reputation: 875
You're setting window.onresize
twice so your first function will never be called.
Try:
window.onresize = function(){
document.getElementById('t_con').style.position = window.outerWidth < 980 ? 'absolute' : 'fixed';
document.getElementById('t').style.position = document.body.offsetWidth < 980 ? 'absolute' : 'fixed';
}
Upvotes: 3