S
S
Sanzhar Bazarbek2021-04-15 18:36:43
AJAX
Sanzhar Bazarbek, 2021-04-15 18:36:43

How to hang a handler on the return event, cancel it and load the previous page manually?

Description: there is a function with AJAX that opens a subpage of the site without a visible reload of the site

async function pageUpdate(event) {

    if (typeof event == 'undefined') {
        $('.detoxNav[href]').click(pageUpdate);
    } else {
        var link = event.target.href;
        event.preventDefault();

        $('body').css('pointer-events', 'none');
        await $('body').animate({ opacity: 0 }, 500).promise();
                
        var html = await $.ajax(link);
        var doc = new DOMParser().parseFromString(html, 'text/html');
        var html = $('body', doc).html();
        history.pushState(null, null, link);
        $('body').html(html);

        pageUpdate();
                
        await $('body').animate({ opacity: 1 }, 500).promise();
        setTimeout(function() {
            $('.preloader').fadeOut('slow', function() {
                $(this).remove();
            });
        }, 500);
                
        $('body').css('pointer-events', '');
    }

}

pageUpdate();

Problem: If you go back to the page - it slows down a little and the same page appears - and not the previous one
Task: it turns out you need to
- hang a handler on the return event?
- Cancel it?
- load past page via AJAX?

As a result, I wrote a code that should cancel the return event:
window.addEventListener('popstate', function(event) {
    alert("STOP");
    event.preventDefault();
}, false);

But, the alert gives, but it doesn't seem to cancel anything. Is that how I started? In which direction to move on? How to implement it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question