Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Кнопка "Показать еще" для категории Opencart 3 (не AJAX)


KDV
 Share

Recommended Posts

Скрипт не AJAX.

 

Как работает:

  • При клике на кнопку в ссылку подставляется &limit=N (отрабатывает совойство location, происходит переход по новой ссылке).
  • Скролит страницу к началу добавленых товаров (если это не необходимо - удалите хвост ссылки "+ '#last-item'" на 31й строке скрипта.)
  • Дизейблит кнопку, если в категории больше нет товаров. 

 

При установке скрипта необходимо указать:

  • кол-во товаров для отображения при клике ( 20 по умолчанию )
  • класс блока обертки товаров
  • класс кнопки

 

(function () {
    // need jquery > v.3
    // add script in 'catalog\view\theme\default\template\product\category.twig' before  footer
    // productWrapperSelector -- selector of product wrapper
    // productToShow -- product`s quantity to show
    // productMoreBtnSelector -- selector of add button

    // config
    const productToShow = 20;
    const productWrapperSelector = $('.product-list');
    const productMoreBtnSelector = $('.more-product-btn');
    // config

    var moreBtn = productMoreBtnSelector;
    var totalViewOnload = productWrapperSelector.children('div');

    function getProductLimit() {
        var totalProductInCategory = {{ results }};
        var productLeft = totalProductInCategory - totalViewOnload.length;

        return productLeft;
    }

    function viewMoreProduct() {
        var loc = location.href;
        var to = loc.search(/&limit/i);
        loc = loc.substring(0, to);
        loc.length == 0 ? loc = location.href : loc = loc.substring(0, to);
        var limit = `&limit=${productToShow + totalViewOnload.length}`;
        
        location = loc + limit + '#last-item';
    }

    function setLastProductId() {
        var lastItemID = totalViewOnload.length - productToShow;
        $(totalViewOnload[lastItemID]).attr('id', 'last-item');
    }

    function moreBtnView() {
        moreBtn.text(`еще ${productToShow}`);
        getProductLimit() <= 0 ? moreBtn.attr('disabled', 'disabled') : '';
        getProductLimit() < productToShow ? moreBtn.text(`еще ${getProductLimit()}`) : '';
    }

    moreBtn.click(function (e) {
        e.preventDefault();
        viewMoreProduct();
        moreBtnView();
    });

    function init() {
        moreBtnView();
        getProductLimit();
        setLastProductId();
    }

    init();

}());

ссылка на Git

 

Edited by KDV
  • +1 4
Link to comment
Share on other sites


  • 7 months later...

С кавычками разобрался.

 

Скрипт рабочий, только нужно заменить строку:

 

var totalProductInCategory = {{ results }};

на

var totalProductInCategory = '{{ results }}';

Чтобы не вылетал синтаксис в ошибку. Огромная благодарность за сей скрипт.

Таже у меня работает на jquery 2.1.1. Так что можно ставить на заводской Опенкарт.

Link to comment
Share on other sites


  • 7 months later...
В 09.11.2018 в 13:57, wgt сказал:

С кавычками разобрался.

 

Скрипт рабочий, только нужно заменить строку:

 


var totalProductInCategory = {{ results }};

на


var totalProductInCategory = '{{ results }}';

Чтобы не вылетал синтаксис в ошибку. Огромная благодарность за сей скрипт.

Таже у меня работает на jquery 2.1.1. Так что можно ставить на заводской Опенкарт.

Всем привет! 

А можно попросить, чуть подробнее описать? Банальной вставкой этого кода - он лезет наружу текстом (скрин)... Шаблон стандартный, OC3.0.2.0. Если можете объяснить, что куда ткнуть - буду крайне благодарен! 

Screenshot_3.png

Link to comment
Share on other sites


  • 1 year later...
  • 1 month later...
В 21.06.2019 в 21:57, kotus2002 сказал:

Всем привет! 

А можно попросить, чуть подробнее описать? Банальной вставкой этого кода - он лезет наружу текстом (скрин)... Шаблон стандартный, OC3.0.2.0. Если можете объяснить, что куда ткнуть - буду крайне благодарен! 

Screenshot_3.png

Нужно его в <script>..код..</script> обернуть и кнопку с классом more-product-btn сделать

Link to comment
Share on other sites


  • 9 months later...

Для начала благодарю за скрипт все работает.

Данный скрипт применил для категорий  

в catalog/view/theme/default/template/product/category.twig

 

 <div class="row">
        {# <div class="col-sm-6 text-left">{{ pagination }}</div> #}
        <div class="col-sm-12 text-center"><button type="button" class="more-product-btn"></button></div>
        
        {# <div class="col-sm-6 text-right">{{ results }}</div> #}
      </div>
      
      {% endif %}
      {% if not categories and not products %}
      <p>{{ text_empty }}</p>
      <div class="buttons">
        <div class="pull-right"><a href="{{ continue }}" class="btn btn-primary">{{ button_continue }}</a></div>
      </div>
      {% endif %}
      {{ content_bottom }}</div>
    {{ column_right }}</div>
</div>
 
{{ footer }} 
<script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>
<script>
(function () {
    // need jquery > v.3
    // add script in 'catalog\view\theme\default\template\product\category.twig' before  footer
    // productWrapperSelector -- selector of product wrapper
    // productToShow -- product`s quantity to show
    // productMoreBtnSelector -- selector of add button
 
    // config
    const productToShow = 20;
    const productWrapperSelector = $('.product-list');
    const productMoreBtnSelector = $('.more-product-btn');
    // config
 
    var moreBtn = productMoreBtnSelector;
    var totalViewOnload = productWrapperSelector.children('div');
 
    function getProductLimit() {
        var totalProductInCategory = '{{ results }}';
        var productLeft = totalProductInCategory - totalViewOnload.length;
 
        return productLeft;
    }
 
    function viewMoreProduct() {
        var loc = location.href;
        var to = loc.search(/&limit/i);
        loc = loc.substring(0to);
        loc.length == 0 ? loc = location.href : loc = loc.substring(0to);
        var limit = `&limit=${productToShow + totalViewOnload.length}`;
        
        location = loc + limit + '#last-item';
    }
 
    function setLastProductId() {
        var lastItemID = totalViewOnload.length - productToShow;
        $(totalViewOnload[lastItemID]).attr('id''last-item');
    }
 
    function moreBtnView() {
        moreBtn.text(`Показать еще ${productToShow}`);
        getProductLimit() <= 0 ? moreBtn.attr('disabled''disabled') : '';
        getProductLimit() < productToShow ? moreBtn.text(`еще ${getProductLimit()}`) : '';
    }
 
    moreBtn.click(function (e) {
        e.preventDefault();
        viewMoreProduct();
        moreBtnView();
    });
 
    function init() {
        moreBtnView();
        getProductLimit();
        setLastProductId();
    }
 
    init();
 
}());
</script>
  • +1 1
Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.