I've written this to display block or display none for a navbar. Though I have a form that submits and display none on the element that is display block by default, which causes there to be no tab that displays active class.
My goal is to be able to hide my div after submit and avoid the classist of null error. Any and all ideas are appreciated. Thanks
// object
const onePage = {
pages: [], // property to save pages in
show: new Event('show'),
init: function(){
onePage.pages = document.querySelectorAll('.page');
//listener for show event, calling function
onePage.pages.forEach((pg)=>{
pg.addEventListener('show', onePage.pageShown);
})
//listener for click event, calling function
document.querySelectorAll('.nav-t').forEach((link)=>{
link.addEventListener('click',onePage.nav);
})
// showing on which page we are viewing
history.replaceState({}, 'Reporting', '#Reporting');
window.addEventListener('hashchange', onePage);
},
nav: function(ev){
ev.preventDefault();
let currentPage = ev.currentTarget.getAttribute('data-target');
document.querySelector('.active').classList.remove('active');
document.getElementById(currentPage).classList.add('active'); // where the error occurs
history.pushState({}, currentPage, `#${currentPage}`);
document.getElementById(currentPage).dispatchEvent(onePage.show);
},
}
document.addEventListener('DOMContentLoaded', onePage.init);
Assign the result to a variable and check if it's null first.
nav: function(ev) {
ev.preventDefault();
let currentPage = ev.currentTarget.getAttribute('data-target');
let curPage = document.getElementById(currentPage);
if (curPage) {
document.querySelector('.active').classList.remove('active');
curPage.classList.add('active'); // where the error occurs
history.pushState({}, currentPage, `#${currentPage}`);
curPage.dispatchEvent(onePage.show);
}
},
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.