简体   繁体   中英

How to combine two javascripts?

Would anyone be so kind as to advise me how to amend this JavaScript please? I'll admit I don't have much experience working with JavaScript and I've tried myself but ended up a bit lost.

To explain, WooCommerce outputs products on my site in .columns-3 and .columns-4, and assigns .first and .last classes accordingly.

If the site is loaded on mobile, the script below will remove the .first and .last tags, and re-assign them to display the products in two columns.

The script currently only targets .columns-3 within function defaultProductRows and function adjustProductRows . I need to also target .columns 4 within the same script, but I'm not sure how to go about adding it.

<script>        
$(window).on('load resize', function (){
  var windowWidth = $(window).width();
  if(windowWidth < 753){ // this is my screen size break point for the rows
    adjustProductRows(); // call the function to adjust add last and first classes
  } else {
    defaultProductRows(); // else if large screen size then get everything back to defalut
  }
});

function defaultProductRows(){
var products = $('ul.products.columns-3 li.type-product');
  products.each(function(idx, li) {
     var product = $(li);
     // remove all classes we added
 $('ul.products li.adjusted-row.first').removeClass('adjusted-row first');
     $('ul.products li.adjusted-row.last').removeClass('adjusted-row last');
  if(idx == 0) { // make sure first li tag gets first class
        product.addClass('first');
  }
  else if((idx+1) % 3 == 0) //this will make sure we have 3 rows by adding last classes after each 3 products
  {
    product.addClass('last');
  }
  else if(idx % 3 == 0)
  {
    product.addClass('first'); // make sure all products divided by 3 will have first       class
  }
  else
  {
    console.log(idx); // just checking for the index
  }


    });
}


function adjustProductRows() {

   var products = $('ul.products.columns-3 li.type-product');
products.each(function(idx, li) {
    var product = $(li);

  if(idx % 2 == 0) // we are even
  {
    product.addClass('adjusted-row first');
    product.removeClass('last');
  }
  else // we are odd
  {
    product.addClass('adjusted-row last');
    product.removeClass('first');
  }


    });

}</script>

Change your selector to include columns-4

From:

var products = $('ul.products.columns-3 li.type-product');

To:

var products = $('ul.products.columns-3 li.type-product, ul.products.columns-4 li.type-product');

This tells jQuery to select li.type-products that are part of either columns-3 or columns-4

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