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

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Visibility of the br tag is not detected

I need to keep one specific div visible on the page while hiding all other content. However, I am facing an issue where the <br> tag inside that div is not showing up. <div id='min320'>min 320px<br>screen width required</div ...

Changes made in React are not reflected in the DOM

import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./index.css"; class App extends Component { constructor(props) { super(props); this.state = { text: "", listItem: [] } this.onChangeInpu ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code: (async () => { const browser = await puppeteer.launch({ headless: false, // slowMo: 250 // slow down by 250ms }); const page = await browser.newPage(); //some code // CODE ABOVE WORKS, ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

What is the optimal method for saving and organizing data in SQL?

I currently have a MySQL table containing data that is displayed in an HTML table. Using JavaScript and drag & drop functionality, I am able to locally sort this table. My question is, what is the most effective method for saving these sorting changes? W ...

Adding a subtle gradient to the image, just ahead of the SVG

Is there a way to achieve this particular look? https://i.stack.imgur.com/yQjvK.png I'm currently encountering this appearance issue. https://i.stack.imgur.com/eQjQ4.png Any suggestions on how I can make it match my desired outcome? Your assistan ...

Admin template system for CodeIgniter

In order to give the Administrator the ability to customize the Admin Dashboard Layout and provide an option for them to upload their own layouts or "Premium" layouts, I need to implement a solution. I have considered one approach: Utilizing CSS (allowin ...

HTML5 canvas game issue: background fails to load

I'm a beginner at designing games using HTML5 canvas. I've been following a tutorial on creating games in the style of Angry Birds from the 'pro html5 games' book. I've completed all the steps in the tutorial, but I'm facing a ...

I am experiencing an issue where the Javascript keydown event does not recognize the character "@" in the EDGE browser

Currently, I am developing a mentioning directive that displays a list of users when the user types in an input field (a div with contentEditable=true). The user can then insert the name of the desired user in a specific format. The list is supposed to be ...

NextJS is throwing an error stating that the function file.endsWith is not recognized as a valid

After upgrading from nextJS version 9.x.x to 12.x.x, I encountered the following error. Any assistance would be greatly appreciated. TypeError: file.endsWith is not a function at eval (webpack-internal:///./node_modules/next/dist/pages/_document.js ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Maximizing page space with ReactJS and advanced CSS techniques

I'm currently in the process of learning CSS and struggling a bit with it. My main issue right now is trying to make my react components fill the entire height of the browser window. I've been using Display: 'grid' and gridTemplateRows: ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

Middleware for enabling the Cross-Origin Resource Sharing (CORS) functionality to efficiently manage preflight

My CORS configuration is set up globally to handle credentials like this: app.use(cors({ origin: 'https://example.com', credentials: true })) However, there are certain routes where I need to allow OPTIONS requests. Following the documentation, ...

Utilizing Codeigniter Ajax to return multiple rows in an ajax call, implementing two conditions (AND) in the SELECT query within the model file

When I click on the 'invoice number' in my 'purchase list', I want to open a collapsible table that will display the list of products matching the invoice number. To achieve this, I am utilizing jQuery to create the collapsible table an ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...