JQuery - Scroll each div with a specific class and apply a new class depending on its width

I had a problem with some jquery and I was wondering if you can help.

I have a menu with a drop-down list and I would like to change the position of the drop-down list depending on which element of the list it is. And how wide the drop-down is, what I still have ...

$(document).ready(function() { var subnavWidth = $('.sub-nav-wrapper').width(); if(subnavWidth > 900) { $('.sub-nav-wrapper').addClass('two-column-offers'); } else if (subnavWidth > 800) { $('.sub-nav-wrapper').addClass('one-column-offers'); } else if(subnavWidth > 600) { $('.sub-nav-wrapper').addClass('offers'); } else if(subnavWidth > 500) { $('.sub-nav-wrapper').addClass('two-column'); } else if(subnavWidth > 300) { $('.sub-nav-wrapper').addClass('one-column'); } }); 

but only takes into account the first element of the list in the menu and applies the corresponding class to each of the auxiliary navigations. I want it to check the width for each sub-navigation not only the first one, and then apply the class to this particular sub.

Hope this makes sense.

+4
source share
3 answers
 $(function() { $('.sub-nav-wrapper').each(function(i,elem) { var width = $(this).width(); if(width > 900) { $(elem).addClass('two-column-offers'); } else if (width > 800) { $(elem).addClass('one-column-offers'); } else if(width > 600) { $(elem).addClass('offers'); } else if(width > 500) { $(elem).addClass('two-column'); } else if(width > 300) { $(elem).addClass('one-column'); } }); });​ 
+5
source

You need to apply this to all menu items, so you want to select all of them using each ();

 $('.sub-nav-wrapper').each(); 

Then you can make your code for "everyone" using the anomonus function.

 $('.sub-nav-wrapper').each(function() { // YOUR CODE HERE }); // End each 

Use the $(this) to perform checks on "every" element.

  $('.sub-nav-wrapper').each(function() { alert($(this).width()); // for example }); // End each 
0
source
  $(document).ready(function() { $('.sub-nav-wrapper').each(function() { var subnavWidth = $(this).width(); if(subnavWidth > 900) { $(this).addClass('two-column-offers'); } else if (subnavWidth > 800) { $(this).addClass('one-column-offers'); } else if(subnavWidth > 600) { $(this).addClass('offers'); } else if(subnavWidth > 500) { $(this).addClass('two-column'); } else if(subnavWidth > 300) { $(this).addClass('one-column'); } }); }); 
0
source

Source: https://habr.com/ru/post/1436847/


All Articles