Reputation: 13
I have some experience in html, css & javascript and I want to start make some projects... I want to make this landing page myself.
nav buttons onclick delay about .3 or .5 then scroll to the section
I tried using setTimeout
in the event but It does not work.
Even I did not get any errors in the console.
I searched a lot about how to use setTimeout()
in events but nothing worked.
Two codes that I tried:
function scrollToClick() {
navbar.addEventListener('click', setTimeout(function (event) {
const clicked = document.querySelector('#' + event.target.dataset.nav)
clicked.scrollIntoView({behavior: "smooth"});
}), 1000)
};
function scrollToClick() {
setTimeout(function(){navbar.addEventListener('click', function (event) {
const clicked = document.querySelector('#' + event.target.dataset.nav)
clicked.scrollIntoView({behavior: "smooth"} );
});}, 100)
};
note: the code scroll no problem but it does not wait
Upvotes: 1
Views: 1722
Reputation: 1938
Put the setTimeout
inside the callback.
function scrollToClick() {
navbar.addEventListener('click', function (event) {
setTimeout( () => {
const clicked = document.querySelector('#' + event.target.dataset.nav)
clicked.scrollIntoView({behavior: "smooth"});
}, 1000)
})
};
An example:
document.getElementById("test").addEventListener('click', function (event) {
setTimeout( () => {
console.log("A clicked happend 1000ms ago")
}, 1000)
})
<button id="test">Click</button>
Upvotes: 1