Issue
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 class="home-section"> </section>
<section class="about-section"> </section>
<section class="gallary-section"> </section>
<section class="project-section"> </section>
<section class="testimonial-section"> </section>
<section class="contact-section"> </section>
<script src="js/scripts.js"></script>
</body>
</html>
Solution
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 class="home-section sec" id="sec1"> section1 </section>
<section class="about-section sec" id="sec2"> section2 </section>
<section class="gallary-section sec" id="sec3" > section3 </section>
<section class="project-section sec" id="sec4"> section4 </section>
<section class="testimonial-section sec" id="sec5"> section5 </section>
<section class="contact-section sec" id="sec6"> section6 </section>
<!-- <script src="js/scripts.js sec" id="sec7"></script> -->
</body>
</html>
Answered By - DRA
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.