Pull to refresh

tagManager2 для MODX Revolution и Scroll вверх страницы при сортировке товаров

Всем привет. Столкнулся с такой проблемой на MODX: при сортировке товаров на сайте Ajax кидал вверх страницы, естественно заказчику это не понравилось, да и кому понравится. Сделанный проект на тяп-ляп это не серьезно.

Начал рыть Google в поисках решений, убил достаточно времени, но все предложенные Fix-ы не катили так, как они были за 2015-2016 года, а тогда версия как бы была на порядок ниже чем сейчас (конец 2018) и многое изменилось.

В итоге пришла идея через средства разработчика в Chrome отследить исполняемый файл и найти функцию которая выдаёт результат сортировки. Поиск увенчался успехом и этот файл назывался filters.js.

Путь к файлу был таким:

/domen_name/public_html/assets/components/tag_manager2/js/web

При осмотре файла была найдена результирующая функция

ajaxRequest: function( state_data )
ajaxRequest: function( state_data ){
        
        if ( typeof state_data == 'undefined' ) {
            $('input[name="page_id"]',tmFilters.config.filters_cont).prop('disabled', false);
            state_data = $('form',tmFilters.config.filters_cont).serializeArray();
        }
        
        tmFilters.ajaxPreload( $(tmFilters.config.products_cont), true );

        //tm_onFilterBefore
        if ( typeof tm_onFilterBefore == 'function' ) {
            tm_onFilterBefore( state_data );
        }

        jQuery.ajax({
            url: tmFilters.config.base_url + tmFilters.config.ajax_url,
            type: "GET",
            cache: false,
            data: state_data,
            dataType: 'json',
            success: function(response) {
                
                if (typeof response.prod_list != 'undefined') {
		    
                    $(tmFilters.config.products_cont).html( response.prod_list );

                    $('html,body').animate({
                        scrollTop: Math.round($(tmFilters.config.products_cont).position().top)
                    });
		    
                }
		
                if (typeof response.pages != 'undefined'){
                    $(tmFilters.config.pages_cont1).html( response.pages );
                    if ( tmFilters.config.pages_cont2.length > 0 ){
                        $(tmFilters.config.pages_cont2).html( response.pages );
                    }
                }
                tmFilters.ajaxPreload( $(tmFilters.config.products_cont), false );
                //tm_onFilterAfter
                if ( typeof tm_onFilterAfter == 'function' ) {
                    tm_onFilterAfter( response.total, response.pageCount, response.onPageLimit );
                }
            },
            error: function(jqXHR,textStatus,errorThrown){
                if(typeof(console)!='undefined') console.log(jqXHR,textStatus,errorThrown); 
            }
        });
        
    },


Теперь вся сложность была в том как реализовать запрет на Scrolling и оставлять пользователя в той части страницы, которая отображается на экране. А всё оказалось довольно таки просто.

Считываем положение Scroll-а:

var scrollTopMyWindow = window.pageYOffset || document.documentElement.scrollTop;

И запрещаем его по считанным координатам, которые уже находятся в переменной scrollTopMyWindow:

$('html,body').stop().animate({ scrollLeft: 0,scrollTop: scrollTopMyWindow}, 200);

Кладём это всё в конец success: function(response) и error: function(jqXHR,textStatus,errorThrown) , затем получаем такой результат:

ajaxRequest: function( state_data ){
        
        if ( typeof state_data == 'undefined' ) {
            $('input[name="page_id"]',tmFilters.config.filters_cont).prop('disabled', false);
            state_data = $('form',tmFilters.config.filters_cont).serializeArray();
        }
        
        tmFilters.ajaxPreload( $(tmFilters.config.products_cont), true );

        //tm_onFilterBefore
        if ( typeof tm_onFilterBefore == 'function' ) {
            tm_onFilterBefore( state_data );
        }

        jQuery.ajax({
            url: tmFilters.config.base_url + tmFilters.config.ajax_url,
            type: "GET",
            cache: false,
            data: state_data,
            dataType: 'json',
            success: function(response) {
                
                if (typeof response.prod_list != 'undefined') {
		    
                    $(tmFilters.config.products_cont).html( response.prod_list );

                    $('html,body').animate({
                        scrollTop: Math.round($(tmFilters.config.products_cont).position().top)
                    });
		    
                }
		
                if (typeof response.pages != 'undefined'){
                    $(tmFilters.config.pages_cont1).html( response.pages );
                    if ( tmFilters.config.pages_cont2.length > 0 ){
                        $(tmFilters.config.pages_cont2).html( response.pages );
                    }
                }
                
                tmFilters.ajaxPreload( $(tmFilters.config.products_cont), false );

                //tm_onFilterAfter
                if ( typeof tm_onFilterAfter == 'function' ) {
                    tm_onFilterAfter( response.total, response.pageCount, response.onPageLimit );
                }
                //Считываем скроллинг на странице
                var scrollTopMyWindow = window.pageYOffset || document.documentElement.scrollTop;
				//Отображаем в консоле результат (для отладки)
                console.log(scrollTopMyWindow);
				//Запрещаем перемещение по считанным координатам, фиксируем
                $('html,body').stop().animate({ scrollLeft: 0,scrollTop: scrollTopMyWindow}, 200);
            },
            error: function(jqXHR,textStatus,errorThrown){
                if(typeof(console)!='undefined') console.log(jqXHR,textStatus,errorThrown);
                
                var scrollTopMyWindow = window.pageYOffset || document.documentElement.scrollTop;
                $('html,body').stop().animate({ scrollLeft: 0,scrollTop: scrollTopMyWindow}, 200);
            }
        });
        
    },

Чистим кеш через панель управления MODX, перезагружаем страницу с помощью Ctrl+F5 и всё, Добби свободен, проблема решена. Надеюсь данная статья помогла Вам в решении проблемы, а судя по тому что я видел на форумах, то таких несчастных было много.

Всем пока, с наступающим 2019!
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.