How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases.

I attempted to calculate the total number of boxes that could fit based on their widths compared to the container width, but realized this logic doesn't account for the fixed order of the items. How can I adjust my code to address this issue?

CodePen Link

Using jQuery:

var itemWidth = 0;
var lineCount = 1;

$(window).on('resize', function(){
  var lineWidth = $('.line').width();
  var itemWidthSum = 0;
  lineCount=1;

  $('.item').each(function(index, element) {
      if(itemWidthSum < (lineWidth - $(element).outerWidth())) {
        itemWidthSum = itemWidthSum + $(element).outerWidth();
      } else {
        lineCount++;
        itemWidthSum = 0;
      }
  });
});

HTML structure:

<div id="container">
  <div class="rect"> 
    <div class="line">
  </div>
    <div class="item">Computer Science</div>
    <div class="item">Language</div>
    <div class="item">Marketing</div>
    <div class="item">Biology</div>
    [...] <!-- Additional item elements -->
</div>

 <h1 class="answer"></h1>

CSS styles:

body {
  padding:25px;
}

.answer {
  position:fixed;
  bottom:0;
  left:0;
}

#container {
  border: 1px solid rgb(200,200,200);
  height: auto;
  width: 30%;
  margin:0 auto;
}

.item {
  padding: 10px;
  background-color: #aef2bd;
  float: left;
}

.rect {
  height: 100px;
  width:100%;
  position: relative;
}

.rect .line {
  position:absolute;
  height:50px;
  width: 100%;
  bottom:0;
  border-top: 1px solid red;
}

Answer №1

After carefully debugging each step, I was able to pinpoint and correct my logic mistake.

Here is the revised jQuery code:

var itemWidth = 0;
var lineCount = 1;


$(window).on('resize', function(){
  var lineWidth = $('.line').width();
  var itemWidthSum = 0;
  var list = [];
  lineCount=1;

  $('.item').each(function(index, element) {
      if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
        itemWidthSum = itemWidthSum + $(element).outerWidth();
      } else {
        lineCount++;
        itemWidthSum = $(element).outerWidth();
      }
  });
});

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

Creating a Vibrant Progress Bar with Multiple Colors: A Step-by-Step Guide

I'm still getting the hang of things, so I apologize if my question isn't perfectly clear. What I'm trying to do is create a dynamic progress bar with multiple colors that animates upon loading the page. I've seen some examples similar ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Obtain image file paths dynamically in a folder using Nuxt

Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing images from a directory using webpa ...

Discovering Constraints on File Size: API Response Encoded in Base64 Visible Within 1 Megabyte, Overcoming Rendering Obstacles

Currently, I am encountering a hurdle in my Next.js application when trying to upload images larger than 1 MB. While the app works seamlessly with smaller images, it faces challenges when dealing with larger ones. Initially, there was a browser console er ...

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: Although I attempted to achieve this functionality using the following method, it appears to be incorrect as it prompts the print dialo ...

Using a data loader with react-router

I am currently working on a react app where I have implemented routes using the new data loaders from react-router-dom import { RouterProvider, createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom'; import Home fr ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Animation for navigation | Struggling to animate only the specific list item

It's late at night and I'm struggling to solve a small problem. Despite feeling tired, I'll ask anyway - even if it makes me look foolish. Here is the code snippet: The HTML: <style> nav.main ul { font-size:175%; font-weight:300; ...

Flexbox transforms Safari's Horizontal Nav into a Vertical layout

Issue with Horizontal Navigation Bar Turning Vertical in Safari I've been using flexbox to adjust the spacing and size of the li elements as the browser window size changes. Everything works perfectly fine in Chrome and Firefox, but for some reason, i ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

Altering the dimensions of Bootstrap's default navbar for a more compact look

Currently, I am attempting to modify the size of Twitter Bootstrap's standard navbar to a smaller dimension. My goal is to have the Brand/logo on the left side, menu options in the center, and social media icons on the right side within the navbar. U ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...

Generate an HTML document from a website page

Having difficulty grasping this concept. I am completely lost on where to begin. It is imperative that I determine how my website can generate a file (whether it be HTML or Text format) and enable users to download it, similar to the functionality in Goo ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Initiate the timer in JQuery

function begin() { rMinutes = Math.floor((Math.random() * 1) + 1); rSeconds = Math.floor((Math.random() * 59) + 1); $('#minutes').text(rMinutes); $('#seconds').text(rSeconds); int1 = setInterval(function timer() { i ...

Tips for simulating next/router in vitest for unit testing?

Struggling with creating basic tests for our Next.js application that utilizes the useRouter() hook, encountering errors when using vitest. In search of solutions to mock next/router for unit testing in conjunction with vitest. ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...