The dilemma of calculating the total width of jQuery's list items

I am in the process of creating a submenu that should look like this:

HTML:

<ul class="mainMenu clearfix">
    <li><a href="#">Eurodan huset</a></li>
    <li><a href="#">Hustyper</a></li>
    <li><a href="#">Galleri</a></li>
    <li><a href="#">10 byggesten</a></li>
    <li><a href="#">Huse til salg</a></li>
    <li><a href="#">Udstillinger</a>
        <ul class="underMenu">
            <li><a href="#">Salgskontorer</a></li>
            <li><a href="#">Velkommen</a></li>
            <li><a href="#">Historie</a></li>
            <li><a href="#">Fremtidens boliger</a></li>
        </ul>
    </li>
    <li><a href="#">Grunde</a></li>
    <li><a href="#">Om os</a></li>
    <li><a href="#">Katalog</a></li>
</ul>

Where .mainMenu represents the main menu and .underMenu contains subpages from the main menu. To ensure the under menu functions correctly, I need to set a fixed width for it (as it has position absolute and the parent <li> element has position:relative, I achieve this by using jQuery.

jQuery/JavaScript:

$('.underMenu').each(function() {
    var t = $(this),
        tW = 0;

    $('li', t).each(function() {
        tW += $(this).outerWidth(true);
    });

    t.css('width', tW);

});

Despite my efforts, the appearance of my under menu does not match my expectations. The current issue is that it appears as follows:

To address this problem, I find that I need to increase the width of .underMenu by an additional 40px; however, I am puzzled as to why this adjustment is necessary given my use of $(this).outerWidth(true);.

Based on my understanding, everything should be working smoothly, but it seems there is a discrepancy between expectation and reality.

CSS:

.mainMenu,
.underMenu {
    clear:both;
    line-height:29px;
    background:url(../images/transPxBlack.png) repeat left top;
    -moz-border-radius:16px;
    -webkit-border-radius: 16px;
    border-radius:16px;
    padding:0 20px;
}
.mainMenu > li {
    margin-left:16px;
    position:relative;
    font-size:13px;
}
.mainMenu > li:first-child {margin-left:0;}

.underMenu {position:absolute;}
.underMenu li {
    font-size:11px;
    margin-left:18px;
}
.underMenu li:first-child {margin-left:0;}

Answer №1

The width calculation function in your code is accurate for adding the widths of child li elements, but it fails to account for padding on the .underMenu element, resulting in an overall shortfall in width. To resolve this issue, include the padding in your calculation as demonstrated below:

$('.underMenu').each(function(){
    var menu = $(this),
        totalWidth = 0;

    $('li', menu).each(function(){
        totalWidth += $(this).outerWidth(true);
    });

    menu.css('width', totalWidth + menu.outerWidth(true) - menu.width());
});

To see the updated code in action, visit this link: http://jsfiddle.net/jfriend00/CTuz3/

Answer №2

The calculations are accurate and functioning properly. To achieve the desired result, include display:inline-block and float:left in the .underMenu li style rule.

.underMenu li {
    font-size:11px;
    margin-left:18px;
    display:inline-block;
    float:left;
}

View the demo to see it in action.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

Find a way to avoid Google's site-blocking measures

Currently developing a website. I am looking into restricting access to only logged-in users on the site. How can I parse the pages in a way that Google does not block the site? ...

Triggering the 'change' event on a hidden value in jQuery can cause issues with knockout dependent observables

Let me share the story of how we stumbled upon this issue... Basically, we were invoking trigger('change') on all our form inputs to notify other knockout observables that their values had been reset. However, we suspect it could be a bug in Knoc ...

What is the best way to eliminate the appearance of the blue square that shows up when the button is clicked on smaller screens?

When testing my project on different screen sizes in Chrome dev tools or on my phone, I noticed a blue square briefly appearing around the button when it is clicked. I attempted to remove this by setting outline: none or outline: 0 on various pseudo-classe ...

Aligning icons side by side using only CSS styling

I'm having trouble positioning icons next to each other horizontally and they keep stacking on top of one another. Can you please review my CSS code to see if I made a mistake? Here is the CSS: #social { top:20px; left:30px; height:32px; width:200p ...

Nested divs with CSS padding inside

I'm curious about the excessive padding above and below the text in this fiddler box. http://jsfiddle.net/fZ6d7/1/ CODE <style> .simplebox { padding: 6px; background: #eee; border-radius: 8px; border: 1px ...

Using jQuery to eliminate accepting input from form field

Looking to switch between a URL input and file input based on user selection of a radio button. Encountering an issue when attempting to remove the accept attribute from the input, resulting in an Uncaught TypeError: $(...).get(...).removeAttr is not a fu ...

CSS to Reverse Align Navigation Bar Text

I'm currently working on my first website and I've encountered a problem with the Navigation Bar. Using CSS rules to align the bar, I noticed that when I apply float:right;, the text floats to the right but ends up aligning backwards on the bar. ...

What is the most effective method for refreshing a control following an Ajax request?

I am currently working on a website that sends an Ajax request to save data to a database. I would like to update the webpage to show the user that their changes have been successfully submitted. I have brainstormed three possible solutions: Immediately ...

Tips for integrating a vertical menu with button icons and subcategories

Currently working on a project with Twitter Bootstrap and looking to create a specific sidebar setup. My goal is to include subcategories using an accordion and a collapsible menu for mobile devices. I came across a similar implementation at http://jsfiddl ...

The HR tag does not display anything following the mailing

Struggling to design a newsletter template with different lines for each product using the HR tag. However, none of my attempts with divs, tables, or CSS properties have been successful. The template looks fine in Chrome, but when sent to the provider, th ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

Problem with Internet Explorer version 9 and above and the Flip Card feature

I have a cool feature for one of my clients where clicking on one div causes another div to flip in its place, like a card flipping over. It's kind of like those portfolio image flippers, but instead of images, it flips divs with content inside. How ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

Selecting a JSON object at random

My data is stored in JSON format. [ ["Apple","A"], ["Orange","O"], ["Grape","G"], ["Kiwi","K"] ] Is there a way to randomly select an array item from this data (e.g. ["Grape","G"])? var letterNum = ""; $.ajax ( { url:"getletter.json" }).done( ...

Get a polished look using HTML and CSS exclusively

Allow me to illustrate what I am intending to accomplish with an example. div{ width:100px;height:100px; border:3px solid #900; border-radius:0px 0px 140px 0px; } <div></div> I am seeking a method to ...

Calculate the total number of vacation days not including holidays and weekend days

Looking for help with a program I've created to calculate total vacation days, excluding weekends and national holidays. Successfully excluded weekends, but struggling with how to ignore national holidays in the calculation. The program is built usin ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...