Is it possible to adjust the width of a parent element based on the number of child

In this particular example, I have structured a header with a logo-container positioned on the left side, a menu in the center, and a button on the right. The menu consists of 5 top-level items and 2 sub-menus.

<div class="container">
   <div class="logo_container">
      <img src="logo.png" />
   </div>
   <div id="top-navigation">
      <div id="top-menu-nav">
         <ul id="top-menu">
            <li class="top-item">Top Item 1</li>
            <li class="top-item">Top Item 2
               <ul>
                  <li class="sub-item">Sub-Item 1</li>
                  <li class="sub-item">Sub-Item 2</li>
                  <li class="sub-item">Sub-Item 3</li>
                  <li class="sub-item">Sub-Item 4</li>
               </ul>
            </li>
            <li class="top-item">Top Item 3
               <ul>
                  <li class="sub-item">Sub-Item 5</li>
                  <li class="sub-item">Sub-Item 6</li>
                  <li class="sub-item">Sub-Item 7</li>
                  <li class="sub-item">Sub-Item 8</li>
               </ul>
            </li>
            <li class="top-item">Top Item 4</li>
            <li class="top-item">Top Item 5</li>
         </ul>
      </div>
      <ul id="menu-button">
         <li class="menu-button-cta">Button</li>
      </ul>
   </div>
</div>

To adjust the width of the parent element based on the number of top-level items in the menu as they are added or removed, various CSS properties can be utilized. For instance:

  • <ul id="top-menu"> has 5 <li class="top-item"> = .container {width: 100%;}
  • <ul id="top-menu"> has 4 <li class="top-item"> = .container {width: 90%;}
  • <ul id="top-menu"> has 3 <li class="top-item"> = .container {width: 80%;}

If you wish to achieve this dynamic adjustment using either CSS or jQuery, it is definitely achievable through appropriate coding techniques and methods.

Answer №1

To achieve this functionality in jQuery, utilize the .children().length method like so:

$("ul.menu-list").each(function() {
    $(this).addClass(".container-" + $(this).children(".menu-item").length);
});

Follow up with some CSS styling:

.container-6 { width: 100%; }
.container-4 { width: 90%; }
.container-2 { width: 80%; }

Answer №2

Here is a jQuery solution I came up with. It calculates the number of children elements first, then adjusts the style accordingly.

var childrenCount = $("#top-menu").children().length;
switch (childrenCount) {
  case 3:
    $(".container").css("width", "80%");
    break;
  case 4:
    $(".container").css("width", "90%");
    break;
  default:
    $(".container").css("width", "100%");
}

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

Ajax: Failed to send POST request (404)

After adding a POST script in the manage.ejs file and console logging the data to confirm its functionality, I encountered an issue. Below is the code snippet: <script type="text/javascript"> var guildID = "<%= guild.id %>"; let data = {so ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

jQuery AJAX request unexpectedly terminates

I am encountering an issue with my ajax calls to a php script that should process the data and display results. Unfortunately, the calls are timing out in both Chrome and Firefox, and appear in red when I inspect them. This is my current ajax code: $.aj ...

Exploring the jungle. Cursor acting strange while dragging

I am currently working on implementing drag-and-drop functionality in my project, utilizing slip.js from slip.js. To enhance the cursor during dragging, I have assigned class="draggable" to each draggable <tr>. The CSS code for this class is: .drag ...

The unexpected postbacks caused by the ASP.NET MVC DropDownList appear to stem from JavaScript, catching me by surprise

In my MVC project, there's a standard form with a dropdown list. Each time I change the dropdown value, the entire page reloads due to a postback. This behavior is unexpected, and I want to prevent the dropdown from triggering a postback. Strangely, ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

Easily automate button clicks on a new tab website

Seeking assistance below, following codes are sourced from "example.com" as assumed: <a href="http://www.example.org" target="vo1" onclick="gp(1)" rel="nofollow">Click Me</a> Upon clicking on ...

JavaScript JSON YouTube API viewCount function is not functioning correctly

I'm struggling to retrieve the views of a video using JavaScript (Chrome Extension). Here is the code I have so far: $(function() { $.getJSON('http://gdata.youtube.com/feeds/api/videos/H542nLTTbu0?alt=json',function(data) { ...

Is it possible for me to move props object deconstruction into a separate module?

Here is my scenario: I have two React components that share 90% of the same props data, but display different HTML structures. I would like to avoid duplicating variable declarations in both component files. Is there a way to extract the common props des ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

Issue with printing JavaScript value using Selenium_ASSUME_WE_NOT have any changes in the content

I'm currently running tests with Selenium and Java. I've experienced success in printing the pages' HTML from JavaScript by using an alert: js.executeScript("alert($('html').html());"); However, when trying to use return, nothing ...

Using Two JavaScript Functions with Identical Names in One HTML File

I am currently facing an issue with a function where the data is retrieved from the getValue() function. The following code snippet is a fragment. grid.js function gridLoadComplete(){ var data = getValue(); } Take into account the following H ...

What is the best way to completely eliminate a div from a webpage

I've created a new div element using jQuery: $(document.body).append('<div id="test"></div>'); Then, I display a success message and remove the div after 10 seconds: $('test').html('SUCCESS!'); setT ...

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...

What is the best method for preventing a form's ajax events from triggering when a link inside the form is clicked?

I am working with an ajax form that looks like this... <form action="/whatever" method="POST" id="blerg"> </form> There is an ajax event attached to it for when the form is submitted: $("#blerg").bind(&a ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...

Restrict the number of dynamic form elements to a maximum of 10 entries

I am working on a feature where users can refer their friends and the data will be saved in a database. <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type='text/javascript' sr ...

Personalizing text in HTML using JavaScript results

I have a modal dialog box function that pops up when a user clicks a button, triggered by a javascript/jquery script. The text displayed in the dialog is set up within an HTML div element that references the script function. My query is how to personalize ...