tay
tay

Reputation: 168

Jquery - Loop through each div with a certain class and apply a new class depending on its width

I'm having trouble some jquery and was wondering if you could help.

I have a menu with a dropdown and would like to change the position of the dropdown depending on which list item it is AND how wide the drop down is, this is what I've got so far...

$(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 list item in the menu and applies the relevant class to each of the sub navigations. I want it to check the width for each sub navigation not just the first one and then apply the class to that particular sub nav.

I hope that makes sense.

Upvotes: 4

Views: 9504

Answers (3)

adeneo
adeneo

Reputation: 318302

$(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');
        }
    });
});​

Upvotes: 6

Teena Thomas
Teena Thomas

Reputation: 5239

   $(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');
   }
 });
 });

Upvotes: 0

SpaceBeers
SpaceBeers

Reputation: 13957

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

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

You can then do your code for "each" with an anomonus function.

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

Use the $(this) keyword to run your checks on "each" item.

 $('.sub-nav-wrapper').each(function() {
    alert($(this).width()); // for example                                      
 }); // End each

Upvotes: 0

Related Questions