0

I am looking to obtain the width of each <li> within the main navigation bar which can be obtained from the main LI. Whilst the below code works it seems to apply the same width to the following LI's rather than detecting it's own individual size.

How would I go about making this dynamic please?

$('.navbar-nav-middle li').width($('.navbar-nav-middle a').parent().width());
1

1 Answer 1

2

You need to use contextual this enclosed with a function here:

$('.navbar-nav-middle li').width(function () {
  return $(this).find("a").parent().width()
});

This might still give the same thing, as <li> takes up its content's width.

4
  • 1
    This is fantastic, thank you very much. Worked a treat!
    – Bradley
    Commented Jan 4, 2017 at 10:48
  • @Bradley Glad to help mate. Commented Jan 4, 2017 at 10:48
  • I'd like to ask, if the user was to resize the screen viewport if we could have this redetect the new LI width if at all possible? as when it hits certain breakpoints the LI may have a smaller font size setting so the width might be slightly less?
    – Bradley
    Commented Jan 4, 2017 at 10:49
  • @Bradley You can detect the resize of window: $(window).resize(function () { ... })... Using @media queries is the best for this. Commented Jan 4, 2017 at 10:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.