Question

We have many divs on the page (see demo below). The container width of divs is not fixed.

How to select the last DIV in the line if user made click on some DIV in the line with jquery?

demo of html: http://jsfiddle.net/F7xHa/

Text Illustration: ( # - is div, X - clicked div, S - need to select this DIV with jquery)

# # # # # - line
# X # # S - line with click
# # # # # - line
# # # # # - line

The idea (maybe not the best): 1. When user click on some DIV (marked X), need to get somehow offset from the top of the page to click position. (width of click on the screen) 2. Then select somehow all visible elements up to click position width) 3. select :last of them.

And maybe it's will help: Im already know how to select the last visible DIV on the page. I use inViewport‎ plugin. But now the task is much harder.

Was it helpful?

Solution

How about something like this:

$('.img').on('click', function(){
    var $self = $(this),
        elements = [],
        selfOff = $self.offset().top;
    $('.img').each(function(){
        if($(this).offset().top == selfOff){
            elements.push($(this))
        }
    })
    elements[elements.length-1].addClass('last')
})

Demo

Might be a better option, but can't think of another one at the moment. This will select only the last one!

If you need to select the elements between the current and the last:

$('.img').on('click', function(){
    var $self = $(this),
        elements = [],
        selfOff = $self.offset().top;
    $('.img').each(function(){
        if($(this).offset().top == selfOff){
            elements.push($(this))
        }
    })
    $self.nextUntil(elements[elements.length -1]).addClass('last')
})

Demo

Or if you like to select all the elements (with the clicked and the last):

$('.img').on('click', function(){
    var $self = $(this),
        elements = [],
        selfOff = $self.offset().top;
    $('.img').each(function(){
        if($(this).offset().top == selfOff){
            elements.push($(this))
        }
    })
    $self.nextUntil(elements[elements.length-1]).add($self).add(elements[elements.length-1]).addClass('last')
})

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top