I'm quite new to developing and I'm right creating my portfolio. I have modal window where the user can display and browse between different projects. I'm using javascript for browsing the project and I've have set the body to prevent body scroll when scrolling the modal window. My problem: How can I create a function so that the content in a modal window scrolls to the top when browsing the next project? Right now you end up at the same position as where you left the previous project.
//Open modal
function openModal() {
document.getElementById("projectModal").style.display ="block";
noScroll();
}
// Close Modal
function closeModal() {
document.getElementById("projectModal").style.display ="none";
addScroll();
}
var projectIndex =1;
showProjects(projectIndex);
function nextProject(n) {
showProjects(projectIndex+=n);
}
function currentProject(n) {
showProjects(projectIndex=n);
}
function showProjects(n) {
var i;
var projects = document.getElementsByClassName("projects");
if (n>projects.length) {
projectIndex =1
}
if (n<1) {
projectIndex= projects.length
}
for (i=0;i<projects.length; i++) {
projects[i].style.display = "none";
}
projects[projectIndex-1].style.display ="block";
}
// Prevent bodyscrolling
function noScroll() {
body.classList.add("noScroll");
}
//Enables bodyscrolling
function addScroll() {
body.classList.remove("noScroll");
}
Just set the scrollTop
of the element to 0:
function openModal() {
var modal = document.getElementById("projectModal");
modal.scrollTop = 0;
modal.style.display ="block";
noScroll();
}
Solution
var modal = document.getElementById("projectModal");
var modalContent = document.getElementById("modalContent");
function openModal() {
modal.style.display ="block";
noScroll();
}
// Close Modal
function closeModal() {
modal.style.display ="none";
addScroll();
}
var projectIndex =1;
showProjects(projectIndex);
function nextProject(n) {
showProjects(projectIndex+=n);
}
function currentProject(n) {
showProjects(projectIndex=n);
}
function showProjects(n) {
var i;
var projects = document.getElementsByClassName("projects");
if (n>projects.length) {
projectIndex =1
}
if (n<1) {
projectIndex= projects.length
}
for (i=0;i<projects.length; i++) {
projects[i].style.display = "none";
}
projects[projectIndex-1].style.display ="block";
modalContent.scrollTop = 0;
}
// Prevent bodyscrolling
function noScroll() {
body.classList.add("noScroll");
}
//Enables bodyscrolling
function addScroll() {
body.classList.remove("noScroll");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.