How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page.

In my HTML structure (specifically for a WordPress theme), it looks something like this:

<ul class="menu">
    <li class="menu-item-has-children menu-item">
        <a>Top Level Page 1</a>
        <ul class="submenu">
            <li class="menu-item-has-children menu-item">Sub Page 1</li>
            <li>Sub Page 2</li>
            <li>Sub Page 3</li>
        </ul>
    </li>
    <li class="menu-item-has-children menu-item">
        <a>Top Level Page 2 which has a different width</a>
        <ul class="submenu">
            <li>Sub Page 4</li>
            <li>Sub Page 5</li>
            <li>Sub Page 6</li>
        </ul>
    </li>
</ul>

I attempted to solve this using CSS initially:

ul.menu li ul {
    width: 100%;
}

However, this ended up making the submenu the same width as the entire ul.menu rather than just the parent page. After trying various methods with no success, I decided to turn to jQuery for help, inspired by a post I found online.

I started with the following jquery code:

$('ul.menu li ul').width($(ul.menu li).width());

Unfortunately, this set all submenus to the width of the first 'li' element, ignoring their individual relationships with parent pages. I then tried several other approaches to target specific elements but none of them seemed to work as intended:

$('ul.menu li ul').width($(this).parent('li').width());

$('ul.menu li ul').width($(this).parent().width());

$('ul.menu li ul').width($(this).parent('li').children('a').width());

$('ul.menu li ul').width($(this).siblings('a').width());

I am wondering if the use of '$this' is incorrect in this context. If so, could you suggest a better approach to achieve what I am attempting?

Answer №1

Stop overcomplicating things:

.menu{
   width: 20vw; //viewport width 
   position: relative;
}

.submenu{
    position: absolute;
    left: 0;
    width: 20vw;
}

If you haven't specified any child elements of .menu as relative or absolute, the submenu will align with the left side of .menu and their widths will be equal.

Suggested Modifications:

Take a look at the CSS rules applied to the elements using Google Chrome inspector. Here are some examples of what can be achieved with CSS:

Natural flow (submenu occupies parent's width): https://jsfiddle.net/cpe0pqhk/

or specific rules https://jsfiddle.net/z011176r/1/

Now, for the jQuery approach:

Before diving into this, keep in mind:

  1. jQuery must be included on the frontend - the code for changing CSS values adds load time for users

    1. When using jQuery, ensure the library is fully loaded before manipulating (hence doc.ready in the example). This might result in a visible change for users on slower connections.
    2. WordPress requires the use of jQuery instead of $ which can cause errors (check your console)

      jQuery(document).ready(function(){
      
      //return a list of dom items that match the selector
      //each iterates over the list
          jQuery('.menu > li').each(function(){
              //this refers to the current element in the list we are working with
              console.log(this);
              var wt= jQuery(this).width();
              //search within this element for the element we want and set width
              jQuery(this).find('.submenu').width(wt);
          });
      })
      

jsfiddle: https://jsfiddle.net/71dyqjvr/1/

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

Error: The method By.cssSelector is invalid and cannot be used

Currently utilizing npm's Selenium Webdriver. Having difficulty getting By.cssSelector to function properly. Other selectors like By.tagName and By.id are working fine. Here is the code snippet: var webdriver = require('selenium-webdriver&apos ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head): wi ...

Using node appendChild() in HTML for animating elements

As someone who is brand new to the world of web development, I am trying my hand at creating a webpage that expands as a button is clicked. Recently, I stumbled upon this helpful link which includes some code: The HTML code snippet is: <ul id="myList" ...

Improving the structure of Vue single-file components

As my single-file component continues to grow, I decided to do some refactoring. It turns out that a couple of dialogs are making the .vue file quite large (800+ lines). To maintain a clean and organized component, I am working on transforming these dialog ...

I encountered an issue while attempting to utilize a JavaScript script - I received an error message stating "Uncaught ReferenceError: jQuery is not defined."

Currently, I am utilizing a template with multiple pages and I need to use one of them. I followed all the necessary steps correctly, but I encountered an error in the console that says Uncaught ReferenceError: jQuery is not defined. Below is my HTML scrip ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

The term 'undefined' does not refer to an object

My div contains the following code: <em id="ProductPrice" class="ProductPrice VariationProductPrice">$75.00</em> I want to change the text color if the value changes. This is what I tried: <script> $(document).ajaxSuccess(function(){ ...

Using an anonymous function in Javascript to change the background color of a div on mouse-over directly from the HTML code

I came across this code snippet in the provided link and as a beginner in JavaScript, I am unsure how to call the JavaScript function from the HTML code. Due to them being anonymous functions, I am struggling to invoke them. Can someone guide me on how to ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

Strategies for adjusting text size to fit within a resizable div container

I'm facing an issue with a resizable div that has text inside. When I resize the div, the last line of the text goes beyond the boundaries of the div. How can I ensure that all the text fits within the resizable div while maintaining the appropriate f ...

Advantages and Disadvantages of Implementing Ajax for Form Validation

Exploring the benefits of validating forms with Ajax, I find it to be a valuable tool in preventing code redundancy. However, before making the switch, I am curious about any potential drawbacks compared to traditional JavaScript validation. While I have c ...

The browser's window.location.href fails to redirect the page

Here are my functions: <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getE ...

Is the parallax effect achieved by stacking one div on top of another div?

Here is a sample of my HTML code: <div id="a" class="panels">FIXED PANEL</div> <div id="b" class="panels">Scrolling-Panel 1</div> <div id="c" class="panels">Scrolling ...

Utilize a singular object to contain multiple instances of the useState hook

const [regionData, setRegionData] = useState({ country: "", city: "", population: "", location: "", temp_min: "" }); Does anyone know a more efficient and cleaner way to replace these individual useState hooks by organizing them into ...

Mark scheduled specific time periods

I need help removing booked time slots from the total time slots. How can I achieve this? Input: Actual time slots: [ '10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00', '12:00-12:30', ...

Is there a way to retrieve the Response object in Express from outside the Route

Currently, my backend API is built using Express JS. Instead of using the res object directly in the route controller, I am looking to access it from a custom service. While I know that I can simply pass res as an argument to the service function and use ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Dynamic background featuring a tall vertical image

I have an image that is extremely long, measuring 2263 x 8192 pixels. I want to design a website with a background that spans the width of the window and the full height of the image, all while maintaining responsiveness. The concept is to have this elong ...

I'm encountering difficulties with customizing the root styling of material-ui's DialogActions

Check out the two buttons in a DialogActions just like this. This is the JSX snippet I'm working with: <DialogActions classes={{ root: classes.dialogActionsLeft }}> <Button autoFocus onClick={() => { setOpen(false); }} ...