Advertisement
bongzilla

Untitled

Jul 4th, 2022 (edited)
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. <script>
  2. document.addEventListener("DOMContentLoaded", function(e) {
  3. const showMoreBtn = document.querySelector(".btn-pocaz");
  4. const productsGrid = document.querySelector(".b-products_grid");
  5. const productCard = productsGrid.querySelector(".b-product-card");
  6.  
  7. const maxProductsGridHeight = productsGrid.getBoundingClientRect().height;
  8. const productsCount = productsGrid.querySelectorAll(".b-product-card_grid").length;
  9.  
  10. const gridRowGap = getGridRowGap(productsGrid);
  11.  
  12. const productCardHeight = getCardHeight();
  13. let rowsCount = getMaxRowsCount();
  14. let openedRowsCount = 2;
  15.  
  16. function getMaxRowsCount() {
  17. return Math.floor(maxProductsGridHeight / getCardHeight());
  18. }
  19.  
  20. function setMaxHeight(height) {
  21. productsGrid.style.maxHeight = `${height}px`;
  22. }
  23.  
  24. function getGridRowGap(grid) {
  25. return parseInt(getComputedStyle(grid).gridRowGap.replace("px", ""));
  26. }
  27.  
  28. function getCardHeight() {
  29. let gridRowGap = getGridRowGap(productsGrid);
  30. return productCard.getBoundingClientRect().height + gridRowGap;
  31. }
  32.  
  33. function triggerResize() {
  34. let el = window;
  35. let event = document.createEvent("HTMLEvents");
  36. event.initEvent("resize", true, false);
  37. el.dispatchEvent(event);
  38. }
  39.  
  40. function changeBtnText(btn) {
  41. let texts = {
  42. "hide": "Скрыть",
  43. "show": "Показать ещё"
  44. }
  45.  
  46. if(openedRowsCount === rowsCount + 1) {
  47. btn.innerText = texts.hide;
  48. } else {
  49. btn.innerText = texts.show;
  50. }
  51. }
  52.  
  53. setMaxHeight(productCardHeight);
  54. triggerResize();
  55.  
  56. showMoreBtn.addEventListener("click", function(e) {
  57. changeBtnText(showMoreBtn);
  58. if(openedRowsCount <= rowsCount + 1) {
  59. let maxHeight = getCardHeight() * openedRowsCount;
  60.  
  61. productsGrid.style.maxHeight = `${maxHeight}px`;
  62. openedRowsCount += 1;
  63. } else {
  64. productsGrid.style.maxHeight = `${productCardHeight}px`;
  65. openedRowsCount = 2;
  66. changeBtnText(btn);
  67. }
  68. });
  69.  
  70. window.addEventListener("resize", function(e) {
  71. let newCardHeight = getCardHeight();
  72.  
  73. setMaxHeight(newCardHeight);
  74. });
  75.  
  76.  
  77. });
  78. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement