Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript.

$(function() {

    changeWidth(500);

    function changeWidth(menuWidth){
        var menuItems = $('#menu li').size();
        var itemWidth = (menuWidth/menuItems)-2;

        $('#menu').css({'width': menuWidth +'px'});
        $('#menu a').css({'width': itemWidth +'px'});
    }
});

You can see it in action here.

I was wondering if there is a way to set the width to be 100% instead of declaring an absolute width like I currently have (500px)?

Thanks in advance!

Answer №1

Check out this improved demonstration: http://jsfiddle.net/MZ2wt/2/

This code essentially adjusts the width based on the <body>. Keep in mind that if your element is not a direct child of body, the results may be unusual. To avoid this, consider passing a reference to the element being resized and use $(this).parent().width() instead of $("body").width()

Answer №2

Adjust the CSS to make the menu 100% width, then modify your function to calculate the menu width and resize the <li> elements accordingly.

Consider using the width() method instead of the css() method to set the width without needing to add "px" at the end of the value.

Additionally, you can implement a resize handler that triggers your function when the window size changes...

Answer №3

After reviewing the jsFiddle example, it appears that you are seeking to make the LI elements' width equal to the UL's width divided by the number of LI elements.

I have made some modifications to your jsFiddle. I changed the LI elements to float left instead of using display inline because inline elements cannot have fixed widths. Additionally, I set the LI elements to have text-align center and transferred the float left property from the A element to the LI element.

You can view the updated jsFiddle here: http://jsfiddle.net/ABC123/27/

$(function() {
    var lis = $('#menu ul li');
    lis.css('width', ($('#menu ul').outerWidth() / lis.length) + 'px');
});

Answer №4

If you're looking to change the width of a menu dynamically, you could try something like this: Check out the demo here

$(function() {

// Function to change the width of the menu
changeWidth(100); // This value could also be set in CSS

function changeWidth(menuWidth) {
    $('#menu').css({'width': menuWidth + '%'});
    var menuWidth = $('#menu').width();
    var menuItems = $('#menu li').size();
    var itemWidth = (menuWidth / menuItems) - 2;

    $('#menu a').css({'width': itemWidth + 'px'});
} });

Additionally, adding a listener for window resize events could provide a more interactive experience. ​

Answer №5

.custommenu1{
    width:100%;
    padding:3px;
    height:30px;
    background-color:#282828;
}

Set the width to 100% for the custommenu1 class and do not specify a width for the menu.

$(function() {

    adjustWidth();

    function adjustWidth(){
        var menuItems = $('#menu li').length;
        var menuWidth = $('#menu').width();
        //alert(menuWidth);
        var itemWidth = (menuWidth/menuItems)-2;

        //$('#menu').css({'width': menuWidth +'px'});
        $('#menu a').css({'width': itemWidth +'px'});
    }
});

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

Utilizing Jquery Effectively to Dynamically Alter Images Based on Ids

HTML Section <div class="features-section"> <div class="container"> <div class="row"> <div class="feat-heading text-center"> <h3>Features</h3> ...

Knockout Mapping is causing a complete re-render of all elements

Utilizing the Knockout mapping plug-in to update the UI with JSON data fetched from the server every 3 seconds. The UI contains nested foreach bindings. However, it appears that all elements within the foreach bindings are completely erased and re-rendered ...

The implementation of $(this).addClass within AJAX success is not yielding the desired results

Currently, I am working on some ajax processing for a click event. Everything is functioning correctly so far, but now I have encountered an issue when trying to add a class in the success function. I am using $(this).addClass("cover");, however, nothing ...

Establishing Fixed Positioning

I'm currently working on fixing the position of an image at the top of a mobile view page. .fixed { position: fixed; } This is specifically for use with Ionic. <div class="item item-image polygon"> <img src="http://urbanetradio ...

How can you insert text onto a page with restricted space?

As I work on my web page, I find myself restricted by a character limit of 10,000. This limitation is proving to be quite challenging for me. The tabs on the page I am editing are divided with div ID, and all my writing already takes up 80% of the charact ...

Organize WordPress loop posts based on tags in real-time

I have integrated a custom loop into my WordPress custom blog page to display all my posts. Here's how I did it: <section class="container blog-article-actu"> <div class="row"> <?php $the_query = ne ...

Optimizing HTML5 metatags and styles for a mobile application

As a C++ developer who has recently delved into using HTML5 for my mobile applications, I am in need of guidance when it comes to fine-tuning my meta tags. While I do have some knowledge in web programming, there are still gaps in my understanding. I am s ...

I am encountering an issue where my input is moving to the following line after the initial one. What could be

Trying to create a layout I like for this form has been a bit of a struggle. I thought I had something good at first, but after the first row of input, the formatting gets all messed up and I can't figure out what's going wrong. <!DOCTYPE htm ...

What's the Purpose of Using an Arrow Function Instead of Directly Returning a Value in a React Event Handler?

After skimming through various textbooks and blog posts, I've noticed that many explanations on event handlers in React are quite vague... For example, when instructed to write, onChange = {() => setValue(someValue)} onChange = {() => this.pro ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

Despite successful installation, node remains elusive on Ubuntu VPS

After installing node using NVM with version 0.25.0, I specifically installed node version 0.10.32. However, upon running node -v, the following error is displayed: -bash: /root/.nvm/v0.10.32/bin/node: No such file or directory Similarly, when executing ...

Troubarked by problems NodeJS faces when trying to establish a connection with CosmosDB using a connection

Having trouble with my code that fails when I try to create a new instance of the CosmosClient. The option to create a CosmosClient using a connection string should be straightforward. The environment variable holds the necessary connection string in this ...

Sort through each individual column in the table

My table filtering code isn't working, and I need to add a status filter with checkboxes. Can someone guide me on how to proceed? var $rows = $('tbody > tr'), $filters = $('#filter_table input'); $filters.on("keyup", fun ...

Interactive drop-down menus created on the fly

I am currently working on dynamically generating inputs using Angular and Angular Material. Each time the user clicks on the Add button, a new dropdown should be created. However, I am encountering an error message that says: 'Error: [$parse:syntax ...

The styling for material UI's default endAdornment is lacking accuracy

My Autocomplete component from material UI v5 includes a default endAdornment icon. However, the icon appears to have the CSS property top:unset, causing it to be styled incorrectly. Here is the code for rendering the Autocomplete: <Grid item xs={3}> ...

Registering the service worker resulted in an error stating "Undefined is not a function"

When attempting to register a service worker using default React code, I discovered that some users were encountering a `TypeError: undefined is not a function` on the line `.then(registration => {` inside the registerValidSW function. Although it works ...

Scrolling horizontally in ng-grid version 2.0.11

In my application, I am utilizing a ng-grid with auto height and width. The challenge arises when dynamically adding columns to the grid. If there are too many columns to display, instead of showing a horizontal scrollbar, the columns shrink in size and ap ...

Utilize jQuery to seamlessly transfer each recorded audio file from rows to corresponding input fields within the table

I have a table below with 2 rows but it can be doubled with a button (Add another Word media) and only one submit button for all rows: <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class=&quo ...

Tips for making an appended element match the height of an image

After embedding the div .soonOverlay into specific .smallCatalogBlock's, I am facing difficulty in adjusting the height of soonOverlay to match only the height of the img within smallCatalogBlock. Currently, its height extends throughout the entire co ...