简体   繁体   中英

The link after e.preventDefault() doesn't load, without jQuery

I want to load a link on click, but it doesn't load. I use preventDefault() to load the animation and setTimeout() . What else should I use?

I try return true , and think to save the path link of the node in a variable and then using location.href to call it. But I don't know how to do it.

<div class="content animated fadeInDown"> Table </div>

<td>
    <a class="link" href="./pizzerias/lazzaroni.html">See More</a>
</td>

<script>
let links = document.querySelectorAll('.link');

links.forEach((link)=>{
    link.addEventListener('click', (e)=>{

        e.preventDefault();
        let content = document.querySelector('.content');

        content.classList.remove('fadeInDown');
        content.classList.remove('animated');

        content.classList.add('fadeOutUp');
        content.classList.add('animated');

        setTimeout(500);
    });
});
</script>

preventDefault is doing exactly what the name implies. It prevents the default behavior of an event.

In the case of a link, the default behavior is to redirect the user to the associated href attribute value.

You are preventing this from happening. So it is never going to happen. The setTimeout isn't doing anything either as it is.

If you want to redirect the user after the animation you need to do it explicitely:

links.forEach((link)=>{
    link.addEventListener('click', (e)=>{

        e.preventDefault();
        let content = document.querySelector('.content');

        content.classList.remove('fadeInDown');
        content.classList.remove('animated');

        content.classList.add('fadeOutUp');
        content.classList.add('animated');

        setTimeout(() => {
            window.location.href = e.target.href;
        }, 500);
});

setTimeout() require a callback function as its first argument but you only pass the time. It would be

setTimeout(() => {
    window.location.href = e.target.href
}, 500)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM