I implemented a procedure to change the style of my top navigation bar based on the user's scroll position on the page:
/* Handling changes in the top nav during page scrolling */
window.onscroll = function ()
{
if ($(window).scrollTop() > 150) // Scrolling is triggered at 150 pixels from the top
{
$('.navbar-default').addClass('scrolling');
}
else
{
$('.navbar-default').removeClass('scrolling');
}
};
However, I noticed that this approach may not be very efficient as the class
of navbar-default
is manipulated multiple times compared to the number of times the onscroll
event is invoked. Additionally, I needed to update an image in the navigation bar based on the scrolling behavior, which led to further complexity:
/* Handling changes in the top nav and image source during page scroll */
window.onscroll = function ()
{
if ($(window).scrollTop() > 150) // Scrolling is triggered at 150 pixels from the top
{
$('.navbar-default').addClass('scrolling');
$('.navbar-default .navvar-brand img').attr('src','image1.jpg');
}
else
{
$('.navbar-default').removeClass('scrolling');
$('.navbar-default .navvar-brand img').attr('src','image2.jpg');
}
};
This situation seems overly complicated. How can I refactor this code and get rid of the bad smell in it?