Multi-tier Dropdown with Dynamic Size Adjustment

I am attempting to adjust the size of a div container within a dropdown menu so that it properly accommodates the text inside.

<div class='dropdown'>
    <button class ="dropbtn"><b>Hover!</b></button>
    <div class='dropdown-content'>
        <div class='dropdown-level2'>
            <button class ="dropbtn-level2"><b>"..."</b></button>
            <div class='dropdown-content-level2'>
                <a>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</a>
            </div>
        </div>
    </div>
</div>

Check it out here: http://codepen.io/anon/pen/BLvxwY

While I could simply set a minimum width, the content is generated dynamically, leading to instances where the text may be shorter than the minimum width requirement.

Any suggestions on how to scale the div accordingly would be greatly appreciated!

Thank you

Answer №1

You can utilize JavaScript to determine the length of your text.

Once you have calculated the text length, adjust the container width using conditional statements such as If, Else if, and Else.

This is how it can be implemented:

$(document).ready(function(){

  $('.dropdown-content-level2 > a').each(function(){

    //calculate text length
    var textLength = $(this).html().length;

    //if the length is under 100 characters
    if (textLength < 100) {

      $(this).css('width', '100px')

    } else {

      $(this).css('width', '200px')

    }

  })

})

In case there are more scenarios to consider:

$(document).ready(function(){

  $('.dropdown-content-level2 > a').each(function(){

    var textLength = $(this).html().length;

    if (textLength < 100) {

      $(this).css('width', '100px')

    } else if (textLength > 100 && textLength < 200) {

      $(this).css('width', '200px')

    } else {

      $(this).css('width', '300px')

    }

  })

})

View the working example on CodePen

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

Can the line "as is" be included in HTML code?

Can I incorporate the following JavaScript and JSON expressions directly into HTML code? CONTRATE > 50 && SALINC <= 50 || RETAGE >= 50 { "CONTRATE": 0, "SALINC": 0, "MARSTATUS": "single", "SPOUSEDOB": "1970-01-01" } I want to be able to ...

Sending text from a Tinymce textarea using Laravel 4.2

I am currently facing an issue with a form that includes a tinymce textarea, allowing users to edit text and save it into a database with HTML tags for display on their profile. The problem arises when Laravel 4.2 escapes the HTML tags, making it difficult ...

Creating a flexible image layout within a container with relative positioning

I attempted to create a basic slideshow with images sliding from right to left as an animation: let slides = document.querySelectorAll('.img-container'); let l = slides.length; let i = 0; setInterval(function(){ i = (i + 1) % l; if(i == 0){ f ...

Tips for minimizing excess white space in Shiny applications

Encountering an issue with plot output in Shiny. When using standard ggplots, the output is correct without any extra white margins. However, when utilizing the "ggmap" package (which also produces ggplot-type outputs), white margins suddenly appear. (Ple ...

Unable to integrate Tailwind CSS in project

Having a bit of trouble with my HTML using Tailwind post CSS. Even though I have installed all necessary packages and linked the CSS, the classes don't seem to be applying. Here is a snippet from the tailwindconfig.js file: module.exports = { conte ...

Tips for aligning inline elements in the center of a webpage

My goal is to center the title in the middle of the page, taking into account its alignment with the search bar. However, I want it to be centered independently and not affected by the search bar's position. Is there a way to achieve this? To better ...

I am encountering difficulties in accessing my component's property within the corresponding template while working with Angular 5

When I call an HTTP POST method to retrieve table names from the backend, I attempt to display them in the template using ngFor. However, the table names are not appearing on the screen. The tNames property is inaccessible in the template. As a beginner i ...

Tips for making a div with a single triangular side using Reactjs

Hey there, I'm looking to design a header similar to the one shown in this image. Can someone provide guidance on how I can achieve this UI using React.js? https://i.sstatic.net/zmW5x.jpg ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Positioning a button on the side of the screen while a hidden side panel is open

I am attempting to create an animation using a side panel that will slide into view when a button is clicked. Here is how it appears when the page loads: https://i.sstatic.net/JPQ2W.jpg When the user clicks on one of the buttons, the notes panel will be ...

Unable to modify the color of the alert notification in JavaScript using React

I've been attempting to create an alert component, but I'm facing an issue with adjusting the color of the alert message. Upon enabling dark mode in the navbar (located at the bottom of the navbar component code), an alert message confirming the ...

Changing the navigation bar's position from fixed to static while scrolling using Bootstrap

I am attempting to keep the navbar at the top by setting a fixed position with 'top: 0' on scroll for navbar-default, and return the navbar to its original position when scrolling up (to top 300). Below is my code: var height = jQuery('.n ...

Select elements in jQuery using both a specific selector and a negative selector

I am currently working with a JQuery function that highlights a specific word and scrolls to it: $('article.node--article p, .video-title').highlightWordAndScroll({ words : search_word, tag : '<span class="found_key ...

Choose a node from descendants based on its attribute

I am working with an interface that switches between displaying different div elements. Each div element has their children arranged differently, and when the switch happens, I need to access a specific child node of the newly displayed div. However, I fin ...

Choosing a checkbox by considering the checkbox value, especially in cases where the checkbox and its label are separate elements

My goal is to click on the checkbox located next to the label "Print Method 1". Take a look at how the element appears here Below is the HTML code for reference: <div class="texter"> <div class="checkbox"/> ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

Troubleshooting issue with RadioButton check change not updating in onPost event in ASP.Net project utilizing Bootstrap HTML and C

Having created two radio buttons, grouped them together, and applied bootstrap classes for styling; I am encountering an issue where the values of the radio buttons are not updating when clicked and submitted. Interestingly, the checkboxes on the same form ...

Collapse the mobile nav bar upon clicking an item

I'm currently facing a challenge with the navigation bar on my event landing page. The issue is that when I open the navbar in mobile view, it does not collapse back after clicking on an item. Instead, it remains open and covers almost 3/4 of the scre ...

Modernized Style - Additional Scrolling Feature for List Element

I've implemented code from Google's Material Design website for my project: https://material.io/components/web/catalog/lists/ Although it works well, the issue arises when more list entries are added and I have to scroll down to view them. The p ...

Can someone assist me in creating a clickable link that opens a menu in HTML when clicked?

I have been attempting for the past few days to open the megamenu by clicking on a link, but despite my efforts, I have not been successful. After reviewing some code, I discovered a clue in the CSS. It seems that setting the visibility value to visible wi ...