Reputation:
I have a JS file that makes #nav
a fixed element when it hits the top of the page (to make a floating nav bar that persists regardless of scrolling). When not at the top of the page, #nav
has rounded corners on the top (border radius top left and top right), which I'd like to disappear when the element is changed to "fixed" This is my code:
$(function() {
// Stick #nav to the top of the window
var nav = $('#nav');
var navHomeY = nav.offset().top;
var isFixed = false;
var $w = $(window);
$w.scroll(function() {
var scrollTop = $w.scrollTop();
var shouldBeFixed = scrollTop > navHomeY;
if (shouldBeFixed && !isFixed) {
nav.css({
position: 'fixed',
top: 0,
});
isFixed = true;
}
else if (!shouldBeFixed && isFixed)
{
nav.css({
position: 'static'
});
isFixed = false;
}
});
});
This doesn't work:
$(function() {
// Stick #nav to the top of the window
var nav = $('#nav');
var navHomeY = nav.offset().top;
var isFixed = false;
var $w = $(window);
$w.scroll(function() {
var scrollTop = $w.scrollTop();
var shouldBeFixed = scrollTop > navHomeY;
if (shouldBeFixed && !isFixed) {
nav.css({
position: 'fixed',
top: 0,
-webkit-border-top-left-radius: 0px,
-webkit-border-top-right-radius: 0px,
-moz-border-radius-topleft: 0px,
-moz-border-radius-topright: 0px,
border-top-left-radius: 0px,
border-top-right-radius: 0px
});
isFixed = true;
}
else if (!shouldBeFixed && isFixed)
{
nav.css({
position: 'static'
});
isFixed = false;
}
});
});
How can I edit the border radius values of #nav from my JS?
Upvotes: 0
Views: 441
Reputation: 5607
Try your best to keep your CSS seperate from your JS. I'd recommend creating a seperate class for the "fixed" version of the element with all of your extra CSS in it, and then removing and adding that class as necessary.
CSS:
#nav.fixed{
position: fixed;
top: 0;
-webkit-border-top-left-radius: 0px;
-webkit-border-top-right-radius: 0px;
-moz-border-radius-topleft: 0px;
-moz-border-radius-topright: 0px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
JS:
$(function() {
// Stick #nav to the top of the window
var nav = $('#nav');
var navHomeY = nav.offset().top;
var isFixed = false;
var $w = $(window);
$w.scroll(function() {
var scrollTop = $w.scrollTop();
var shouldBeFixed = scrollTop > navHomeY;
if (shouldBeFixed && !isFixed) {
nav.addClass("fixed")
isFixed = true;
}
else if (!shouldBeFixed && isFixed)
{
nav.removeClass("fixed")
isFixed = false;
}
});
});
Much neater, no?
Upvotes: 2