Which li in the row is the final target?

In my list of items, there are no special classes assigned to the list items.

<ul>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  etc..
</ul>

When displayed on the front end, it appears like this:

I am trying to target the last li in each row (the ones highlighted in green). However, since these li elements do not have any defined classes and their positioning varies based on screen size, I am unsure how to achieve this. Is there a way to specifically select the last li in a row?

Edit: To clarify, all li items are within a single ul.

Answer №1

function checkItemsInRow() {
    var itemsInRow = 0;
    $('ul li').each(function() {
        $(this).removeClass("highlight");
        if($(this).prev().length > 0) {
            if($(this).position().top != $(this).prev().position().top) {
               $(this).prev().addClass("highlight");
            }
            itemsInRow++;
        } else {
            itemsInRow++;   
        }
        if($(this).next().length > 0) {
        
        } else {
            $(this).addClass("highlight");
        }
    });
}

checkItemsInRow();

$(window).resize(checkItemsInRow);

JSFIDDLE

I believe I have found the solution... Please verify by resizing the window.

Answer №2

Here is a custom function that I created to address a similar issue and you are free to customize it as needed: CUSTOM FUNCTION FOR RESIZING

VIEW DEMO (resize)

var resizeDetector = function(element) {
var $elem = $(element);
var container = $(element).parent();
var containerWidth = container.outerWidth();
var toggleButton = $('#main-menu-wrapper.main-menu-expanded #header-toggle-buttons');
container.attr('data-width', containerWidth);
var totalElemWidth = 0;
$elem.each(function() {
    totalElemWidth += $(this).outerWidth();
});

var newContainerWidth = container.outerWidth();
var currentWidth = 0;        
$elem.removeClass('lastInRow last-row');
$elem.each(function() {
    var item = $(this);
    var elemWidth = item.outerWidth();
    currentWidth += elemWidth;        
    if (currentWidth > newContainerWidth) {
        item.prev().addClass('lastInRow');
        currentWidth = elemWidth;
    }
    item.attr('data-curWidth', currentWidth);        
});
var lastInRow = $(element + '.lastInRow');

if (lastInRow.length > 0) {
    lastInRow.last().nextAll().addClass('last-row');        
} else {
    $elem.addClass('last-row');
}
}

resizeDetector('li');  

INCLUDE THIS SECTION

$(window).resize(function() {
  resizeDetector('li');
});

Answer №3

Consider this elegant solution using ONLY CSS:

To achieve the desired layout, we can implement a set of media queries that specifically target the last item in each row and modify its color accordingly.

While this task may seem daunting, employing a preprocessor like LESS can simplify the process and reduce the chances of errors. By defining variables within the LESS mixin to suit our requirements, we can effortlessly obtain the desired layout. Take a closer look at the implementation below...

CODEPEN (Try resizing to witness it live)

The usage is straightforward - just invoke the LESS mixin as follows:

.box-layout(boxItemList, li, 100px, 120px, 2, 7, 20px);

This mixin takes 7 parameters:

1) Selector for the list

2) Selector for the items

3) Item width

4) Item height

5) Minimum number of columns

6) Maximum number of columns

7) Margin value

You can customize these parameters to fit your specific needs and obtain the desired layout effortlessly

DEMO #2

Here's the CSS (LESS) code snippet provided:

.box-layout(@list-selector, @item-selector, @item-width, @item-height, @min-cols, @max-cols, @margin)
{
   // mixin content here...
}

.loopingClass (@layout-width, @next-layout-width, @min-cols) {
   // additional function logic here...
}

.box-layout(boxItemList, li, 100px, 120px, 2, 7, 20px);

Answer №4

Here is a method using jQuery to calculate the sizes of the container ul and the inner elements for achieving a specific layout.

This approach requires:

  1. All <li> elements are structured like cells in a table, each taking up the same width (including margins).
  2. The .last-type class is applied to relevant <ul> elements.

jQuery:

$(function(){

    resize();

    $(window).resize(function(){
        resize(); 
    });
});

function resize()
{
    var ul = $("ul.last-type");
    ul.each(function(){
        var ulWidth = $(this).width();
        var liWidth = $($(this).find("li")[0]).outerWidth(true);
    
        var lisPerLine = parseInt(ulWidth / liWidth);
        $(this).find("li").removeClass("marked");
        $(this).find("li:nth-child("+lisPerLine+"n)").addClass("marked");
    });

}

CSS:

ul
{
    list-style: none;
    margin: 0;
    padding: 0;
    font-size: 0;
}

ul li
{
    display: inline-block;
    width: 75px;
    height: 75px;

    background: blue;
    margin: 15px;
    font-size: 100%;
}

ul li.marked,
ul li:last-child
{
    background: green;
}

JSFiddle


Edit:

To address discrepancies on certain screen sizes, set zero font-size on the parent <ul> element and define the actual font-size in the <li> elements.

ul
{
    font-size: 0;
}

ul li
{
    font-size: 100%;
}

Additionally, include the ul li:last-child selector in the same rule as ul li.marked to ensure the last element on the last line is always marked, even if it does not reach the end of the line.

Answer №5

If I understand your question correctly, you are asking about the scenario where every list item has the same width.

Here is a JavaScript function that addresses this:

function getLastItem(){
    $('li').removeClass('hello');
    var containerWidth = $('ul').eq(0).width();
    var totalItem = $('li').length;
    var itemWidth = $('li').eq(0).outerWidth(true); // accounting for margin
    var itemPerRow = Math.floor(containerWidth/itemWidth);
    var totalRows = Math.ceil(totalItem/itemPerRow);
    $('li:nth-child(' + itemPerRow + 'n), li:last-child()').addClass('hello');   
}

Feel free to use this code in your project and see how it works!

Check out the demo here

Answer №6

One strategy is to analyze the pixel distance between each final li element and the border. The offset function calculates the top and left distances.

var position = $("#target").offset();
display("The target is positioned at " + position.left + "," + position.top + " in the document");

Determine a reasonable maximum distance the last li element will be from the border, and then implement this logic:

var screenWidth = $(document).width();
var rightDistanceFromWindow = screenWidth - document.getelementsbyclassname("li").offset().left
if (rightDistanceFromWindow < reasonableMaximumDistance)
/*Change the color to green*/

Answer №7

My method involves determining the number of columns in each row and then using a loop to set background colors accordingly.

JavaScript Code:

function countColumnsInRow() {
    var columnsInRow = 0;
    $('ul li').each(function() {
        if($(this).prev().length > 0) {
            if($(this).position().top != $(this).prev().position().top) return false;
            columnsInRow++;
        }
        else {
            columnsInRow++;   
        }
    });   

    $("ul li").css("background","#ffffff");

    for(i=columnsInRow; i<=$('ul li').length; i=i+columnsInRow)
    {
       $("ul li:nth-child("+i+")").css("background","green");
    }
    $("ul li:last-child").css("background","green"); 
}

countColumnsInRow();

$(window).resize(countColumnsInRow);

View Demo on JSFiddle

Answer №8

This solution focuses on comparing the left offset of each element with its parent's offset and any margins applied to the li elements.

By examining the left offset and adjusting for margins, it identifies the end of a row when the offset matches the parent’s. This is true for both the previous element in a row and the last child of the UL.

A special class is added to the last item in each row, which allows for customization using CSS. The function is also triggered by window resize events.

The solution does not rely on specific widths for elements.

var resizeTimer;

function identifyLastInRow(){
     var $list = $('ul'),
        offsetLeft = $list.offset().left,
        leftMargin = 5;
   /* Reset */
    resetLastInRow($list);
    /* Find end of rows and apply class */
    $list.children().each(function (i) {
        var $li = $(this);                   
        if ($li.offset().left === offsetLeft + leftMargin) {
            $li.prev().addClass('to-hide');
        }
    }).last().addClass('to-hide');    

}

function resetLastInRow($parent){
    $parent.children().removeClass('to-hide');    
}
/* Initialize on resize event and trigger on page load*/
$(window).resize(function(){
    /* Throttle resize event */
    if(resizeTimer){
       clearTimeout(resizeTimer); 
    }
    resizeTimer = setTimeout(identifyLastInRow, 50);

}).resize();

DEMO

Answer №9

var bar = document.getElementById('bar');
// returns: Fourth  (4)
console.log(bar.lastElementChild.textContent);
<ul id="bar">
  <li>One (1)</li>
  <li>Two (2)</li>
  <li>Three (3)</li>
  <li>Fourth (4)</li>
</ul>

Answer №10

Understanding the number of elements in each row is essential for utilizing this method

$('li:nth-child(Xn)')

In this case, X represents the quantity of elements in each row. To apply this to the provided screenshot, use:

$('li:nth-child(10n)')

Answer №11

To access the last child element, you can use the following code snippet:

 $('ul li:last-child').css('color','red');

Answer №12

Give this a shot:

function fetchLastItem(){
var lastElement=$("ul>li:last-child");
// Perform actions on the lastElement, representing the final li child of your ul element.
}

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

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

Adding images to .xsl using XML

I have created a unique "blog" using XML and XLST. The format of the blog is as follows: <post id="1" category="Miscellaneous"> <ptitle>MiG-21</ptitle> <psubtitle>Mikoyan-Gurevich MiG-21</psubtitle> <image></image& ...

The ion-col with col-3 is causing a template parse error

Currently, I am facing an issue while trying to print data from a constructor. Everything is working fine until I added col-3 to ion-col. It seems like I missed including some module, but I am not sure which one. This is my home.ts file: import { Compone ...

Using Jquery to store a JSON object in a global variable

Trying to pass a JSON object from an AJAX call into a variable for use in another function has been a bit tricky. Unfortunately, when attempting to console.log() the variable ($aR), it keeps returning "undefined". Check out the code snippet below: $aR = ...

Difficulty in retrieving attribute information from an image - JQuery

I have been attempting to extract the attribute from images that I have obtained from a collection of ul-based image galleries using the clone function. Here is the Ul Tag I am trying to clone: <ul class="bannerscollection_zoominout_list"> ...

Unable to display the response received in jQuery due to a technical issue with the JSON data

Hey there! I'm fairly new to JSON and web development, so please bear with me if I'm not explaining the problem in the most technical terms. I recently encountered an issue where I retrieved a JSON response from a website, but I couldn't di ...

Struggling to effectively transfer a callback function within a series of functions

I am currently utilizing the codebird library to make requests to the Twitter API. The responses from these requests are functioning as expected, but I am looking to pass that response along to my route. Below is a segment of my route.js: router.get(&apos ...

What specific CSS attribute changes when an element is faded out using jQuery's FadeOut method?

When we make an element fade in or out, which specific CSS property is being altered? Is it the visibility attribute, or the display property? I am hoping to create a code snippet with an if statement condition that reads (in pseudo code): if the div is ...

Error: Unable to locate module: Unable to resolve 'next/web-vitals'

I keep encountering the following error message: Module not found: Can't resolve 'next/web-vitals' I am interested in utilizing the **useReportWebVitals** feature from next/web-vitals. For more information, please visit: Optimizing: Analyt ...

Striped shadows in React Three Fiber

Currently in the process of developing a basic 3D object viewer website using Next.js and React-Three-Fiber. Everything was running smoothly until I added a DirectionalLight instance and attempted to make all meshes receive shadows. https://i.sstatic.net/ ...

Select the element to emphasize it and reduce the visibility of others

I'm currently facing an issue with a block that contains multiple divs representing products. My goal is to have the selected product highlighted while the rest appear less prominent when clicked. I've managed to achieve this functionality, howev ...

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...

Using the import statement to bring in module one from "./two" is causing a malfunction in my JavaScript file while working with Laravel 5.4 broadcasting using Pusher

Node Version 8.6.0 npm version 5.3.0 Chrome Issue (Version 61.0.3163.100) Error: Unexpected token import Mozila Problem (Version 56.0 (64-bit)) SyntaxError: Only top-level import declarations are allowed import one from "./two"; ...

What methods can I use to ensure the accuracy of my form and securely store my information in a database using Angular,

I am currently working on an Angular project where I aim to create a form, validate it, and store data in my database using PHP and MySQL. However, I have encountered some challenges while attempting to accomplish this task. Here are the errors that I have ...

Troubleshooting Problem with Matching Heights in Bootstrap Columns

I am experiencing an issue with the bootstrap grid columns on my site not having equal heights. The problem arises when a product name contains a long text, causing height discrepancies among the columns. Despite trying to fix the height issue by adding tw ...

Is there a way to incorporate a variable into a JSON URL?

I'm attempting to incorporate a variable I have defined into the JSON URL: var articleName = "test"; $.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType= ...

Dynamically updating fields in PHP using jQuery's passed variable

In my web application, I have a selection of locker numbers available in a dropdown list that is populated from MYSQL/PHP. My goal is to display each locker's combination and location when a user selects a locker number from the dropdown list on the s ...

The ts-loader seems to be malfunctioning (It appears that a suitable loader is required to handle this file type, as no loaders are currently set up to process it)

I'm currently in the process of integrating TypeScript into a JavaScript project, but it seems like webpack is not recognizing the ts-loader for files with the .tsx extension. I've attempted to use babel and even tried awesome-ts-loader, but none ...

Navigate to a particular section in the webpage

There are a few div elements with the class .posts that each have an attribute data-id which corresponds to the ID in a MySQL database. <div class="posts" data-id="1"></div> <div class="posts" data-id="2"></div> If I want to scrol ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...