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

Minimize the gap between legend text and icon in Highchart

Is there a way to decrease the space between the number and icon? I am currently working with Angular 8 and Highchart. Below is the configuration of the chart legend. https://i.stack.imgur.com/0dL7y.jpg this.legend = { align: 'center', verti ...

Change the identifier of a value within the React state

I am currently working on a form that includes input fields for both keys and values. The goal is to allow users to edit key value pairs, where editing the value field is straightforward, but editing the key field requires updating, removing, and tracking ...

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

A guide to dynamically display input fields according to the selected mat-radio button in Angular Material

I am currently utilizing angular material version 9.2.4 Within my project, I am implementing the angular material mat radio button with an input field. Each payment method will have its own corresponding input field. When the 'Cash' option is se ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

iPhone has trouble accessing alternative forms of content

<object width="300" height="100" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param value="5352f5c8e96c251fb9d79890f2294608.swf" name="movie"> <!--[if !IE]>--> <object width="300" height="100" data="5352f5c8e96 ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

Unexpected response from http.request in NodeJS

When using the http.request module, I encountered a strange issue. My goal is to write a web crawler in NodeJS to fetch and parse data from this webpage. However, the response provided by http.request does not match the HTML rendered by Chrome. Below is ...

Ways to update state based on changes in localStorage values

Is there a way to update the state when the value of localStorage changes? For instance, I have a language switch button for French and English. When I click on English, it gets stored in localStorage. How can I ensure that the entire project switches to t ...

The Angular Ivy strictTemplates error message states that the type 'Event' cannot be assigned to the type 'InputEvent' parameter

I'm feeling lost trying to figure out what's wrong with this code snippet: <input #quantity type="number" matInput formControlName="quantity" (input)="onQuantity($event, i)" placeholder="Quantity"/> onQuantity(event: InputEvent, i: number ...

Sorting or filtering with two elements in the option value in AngularJS

I have been struggling for a while now to find a solution to this issue. How can I display the query for the third option value, which should show the filter of DB || CSLB from a json file? <select ng-model="search.source"> <option value="DB"& ...

Click on a pricing category when the page is updated with jQuery Ajax

My code is experiencing an issue. When the prices tab is empty, I can select one with a CSS highlight. However, after refreshing the tab using jQuery and ajax, the selection style stops working. Below is my HTML code: $('#subcategories').on(& ...

"Concealing specific routes in Vue Router depending on a certain condition - what's the

I need to determine which routes to hide based on a condition that evaluates to true or false. I have a collection of routes, such as: - Products - Clients For instance, if a user logs in but does not have the permission to edit products, then the updated ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

Unable to retrieve list using Selenium in C# due to issues with FindElements method

Currently, I am working with C# and NUnit. I have encountered an issue where I need to extract the value from a span element and store it in an ArrayList. This is the code I am using to retrieve the price list: var productprice = driver.FindElements(By. ...

What is the best way to rate a particular image?

while ($row = mysqli_fetch_array($result)) { echo ""; echo "<div id='img_div'>"; echo "<i class='fas fa-times'></i>"; echo "<img class='photoDeGallery' s ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

How can I retrieve the child of a specific selector using jQuery?

I'm having trouble articulating my issue clearly. I need to retrieve the child of a tag that I previously selected. Here's a simple code example: This is the HTML code: <div class="inner"> <div class="box"> <a href="yagh ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Revamping jQuery for a React component

As I transition away from using jQuery for quick hides, shows, and CSS changes in favor of React components that require re-rendering without triggering the jQuery actions requiring a page refresh, I find myself needing to set state within each component. ...