This code snippet adds a reading progress bar to a webpage. The bar visually represents the user's scroll progress through the main content area. Let's break down how it works and improve it.
The code attempts to calculate the progress based on the scroll position relative to the total height of the main
element. However, it has several issues:
div
is created, but no styling or progress update logic is present.totalHeight
might be inaccurate depending on the page structure. Using outerHeight(true)
includes margins, which might not be desired. It also doesn't account for dynamic content that might change the height after the initial calculation.footerHeight
might lead to incorrect progress calculation if the footer is fixed or overlaps the main content.Here's an improved version that addresses these issues:
<code class="language-javascript">$(document).ready(function() { if ($('body').hasClass('single')) { const progressBar = $('<div id="reading-progress"></div>'); $('header').after(progressBar); let totalHeight = $('main').height(); // Use height() for more accurate calculation let windowHeight = $(window).height(); $(window).on('scroll', function() { let scrollTop = $(this).scrollTop(); let progress = (scrollTop / (totalHeight - windowHeight)) * 100; // Adjust for window height progress = Math.min(progress, 100); // Cap progress at 100% $('#reading-progress').css('width', progress + '%'); }); } });</code>
This improved code:
div
with the ID reading-progress
to act as the progress bar.height()
: It uses height()
instead of outerHeight(true)
for a more accurate calculation of the main content height.$(window).on('scroll', ...)
to continuously update the progress bar's width as the user scrolls.#reading-progress
div. For example:<code class="language-css">#reading-progress { height: 5px; /* Adjust height as needed */ background-color: #007bff; /* Adjust color as needed */ position: fixed; top: 0; left: 0; width: 0; /* Initially 0% width */ z-index: 1000; /* Ensure it's on top */ }</code>
Remember to include jQuery in your project for this code to work. This revised code provides a more robust and accurate reading progress bar. Further refinements could include handling edge cases and adding more sophisticated styling.
The above is the detailed content of Reading Progress Bar. For more information, please follow other related articles on the PHP Chinese website!