Tips for adjusting the width of dynamic list boxes according to user input

When a list box is clicked, it will be removed and replaced by 'n' new list boxes of the same type. The value of 'n' is provided by the user in a prompt. This process can be repeated.

The width of the newly generated list boxes should not be the same as the original one that was clicked. If the original list box had a width of '200px', then the width of the new items should be '(200/n) px'.

The position of the newly generated list boxes should be at the exact same spot as the clicked one, one after the other. Also, their widths should be reduced by n as mentioned above.

I have seen suggestions to use methods like After() or InsertAfter(), but I am unfamiliar with JavaScript and jQuery so I am unsure how to implement them in this scenario.

Here is the HTML code:

<h4>Rhythm-Ruler</h4>
<div>
   <ul class="list">
     <li></li>
   </ul>
</div> 

And the JavaScript code:

$("ul").delegate("li", "click", function(){
   var inputNum = prompt("Divide By:"); 
   if(inputNum > 1){
       $(this).remove();
    }

    for (var i = 1; i <= inputNum; i++){
       var newList = document.createElement("li");
       $(".list").append($(newList).text(i));
       $(this).css('width', 200/inputNum + 'px');
    }
});

As for the CSS:

  li {
      float: left;
      list-style: none;
      width: 200px;
      height: 30px;
      box-shadow:0 -1px 1em hsl(60, 60%, 84%) inset;
      background-color: #FF7F50;
      display: inline;
      text-align: center;
      padding: 2px;
   }

For reference, you can view the JSFiddle here: https://jsfiddle.net/yoshi2095/gwpf42ds/6/

Answer №1

Check out the updated fiddle with a working example.

https://jsfiddle.net/z90hg3z5/

$("ul").delegate("li", "click", function()
{
   var inputNum = prompt("Enter number to divide by:");
   if(inputNum>1){
       var i;
       var width = $(this).width();
       $(this).remove();
       var newWidth = width/inputNum;
    }
    else 
    {
         newWidth = width;
    }
    for (i=1;i<=inputNum;i++)
    {
        var newList=document.createElement("li");
        $(".list").append($(newList).text(i));
        $(newList).css('width', newWidth);
    }
});

To explain, you need to calculate the width of the clicked element in order to perform division by the input number. After that, the original element is removed and the new elements are inserted in the correct place.

Check out the updated code below:

$("ul").delegate("li", "click", function()
{
    var inputNum = prompt("Enter number to divide by:");
    if(inputNum>1)
    {
         var i;
         var width = $(this).width();
         var newWidth = width/inputNum;
     }
     else 
     {
         newWidth = width;
     }
     for (i=1;i<=inputNum;i++)
     {
         var newList=document.createElement("li");
         $(newList).text(i).css('width', newWidth).insertAfter($(this));
     }
});

Improved code formatting for better readability.

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

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...

Arranging the Logo and hamburger menu for optimal visibility

I am having trouble aligning a CSS hamburger menu next to my logo. I have placed both the CSS hamburger and the logo in the header. Although I was able to float the logo to the right, it is not on the same line as the menu. After the header, I would like ...

Leveraging CSS keyframes to create dynamic animations

I am facing an issue with CSS while designing my website. I reached out to the plugin developer for help through a ticket submission, but unfortunately, I have not received a response yet. On my homepage at , I have utilized CSS keyframes to create a text ...

Guide to displaying PHP output in a format suitable for plotting

I'm currently working on plotting PHP output from a MySQL database using . The desired format for the output should look like this - var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], ...

How can I generate a .json file that includes PHP variables?

How can I create a customized JSON file called "file.json.php" using PHP variables such as $_POST['foo']? This file will produce different results based on the value of the post variable passed through an ajax call. What settings do I need to imp ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Having difficulty accessing POST data through $.ajax request

I am currently working on a simple JavaScript code that is set up to send POST requests to my local server. The JavaScript and PHP files are both located on localhost, so I don't have to worry about any cross-site issues for now. Here is the JavaScrip ...

isolating child pointer events in CSS styling

I am looking for a way to prevent the click event on the checkbox from triggering the parent click event that opens a modal. Check out this gif demonstrating the issue: https://gyazo.com/856a84242349609f4506095de33ee1df Let me explain further what's ...

Header reference differs from the document referrer

this is the request header: GET / HTTP/1.1 Host: localhost:3002 Connection: keep-alive sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 User-Agent: ...

Utilizing Angular's ngShow and ngHide directives to hide spinner when no data is retrieved

I'm having an issue with the HTML code below. It currently displays a spinner until a list of tags is loaded for an application. However, the spinner continues even if no events exist. I want to make the spinner disappear and show either a blank inpu ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

Fuzziness occurrence in distinct vue element

My Situation I have a custom DropDown with a filter text input above. The DropDown can be opened independently from the filter text input. My Goal I want the DropDown to close when the filter input loses focus and also when I click outside of the Drop ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...

Add a personalized class to a mat-tab within a mat-tab-group

I am looking to add unique styles to specific mat-tabs within a mat-tab-group based on a condition. The main mat-tab-group already has a default custom style that is functioning correctly. The styling is applied as follows: .mat-mdc-tab-group.round-tabs, ...

What are the steps to customize the color of my navigation bar?

Currently, my website has a navigation bar with links that turn white after being clicked or visited, but I am struggling to make them white initially. Here is the code snippet for my HTML: <nav> <ul> <li><a href="index.html" ...

The JavaScript value of the button text once it has been modified

We have a website feature where the button text changes dynamically. Here are the elements before the button text change: <button _ngcontent-wex-c70="" class="btn btn-wait buy font-family-title height-70 pp-sun-ins"><labe ...

Utilize AngularJS to loop through a list with ng-repeat

Seeking guidance as an Angular newbie. The ng-repeat in question is formatted as: ng-repeat="f in drillDownList['D' + d.merchMetrics.DEPT_NBR + 'CG' + d.merchMetrics.CATG_GRP_NBR + 'C' + d.merchMetrics.DEPT_CATG_NBR] M ...

When I apply the overflow hidden property, the wrapped text magically disappears

Looking for a solution to the text wrapping issue in this content---> trying to figure out what can be done here as I am testing the waters and exploring new territory with my work. Am I getting closer? Or farther away? Testing, testing, ...