This is a one page index.html
website. I want to fixed the position of each section even after browser refresh. How can I modify main.js
for required JavaScript codes for this changes?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Page Title</title>
<meta name="description" content="My Page Description">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<section > </section>
<section > </section>
<section > </section>
<section > </section>
<section > </section>
<section > </section>
<script src="js/scripts.js"></script>
</body>
</html>
CodePudding user response:
You can do something like this:
const currentURL = window.location.protocol "//" window.location.host window.location.pathname;
let sections = document.querySelectorAll('.sec')
sections.forEach(function(item){
window.addEventListener("scroll",()=>{
if(isScrolledIntoView(item)){
window.history.replaceState("", item.id , `${currentURL}#${item.id}`);
}
})
})
// this is not my code, found it in stackoverflow
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
.sec{
width: 100%;
height:400px;
border: 1px solid black;
display: flex;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Page Title</title>
<meta name="description" content="My Page Description">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- <link rel="stylesheet" href="css/styles.css?v=1.0"> -->
</head>
<body>
<section id="sec1"> section1 </section>
<section id="sec2"> section2 </section>
<section id="sec3" > section3 </section>
<section id="sec4"> section4 </section>
<section id="sec5"> section5 </section>
<section id="sec6"> section6 </section>
<!-- <script src="js/scripts.js sec" id="sec7"></script> -->
</body>
</html>