Nima Nima - 6 months ago 89
Javascript Question

jQuery: Detect the position inside Flexbox

I have several boxes, using Flexbox as container and list tags as boxes inside. They're responsive and change position as you resize the width. I am trying to figure out a way via jQuery to detect which boxes are touching the left side and which are touching the right side so I can

addClass
of
right
or
left
to them based on their position for styling. I think it's possible using offset to achieve this which I'm figuring out how to start. Any ideas?

JSFiddle


.container {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
flex-direction: row;
list-style:none;
}
li {
border:10px salmon solid;
padding: 25px 15px;
text-align: center;
font-size: 1.2em;
background: white;
flex-grow: 3;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="container">
<li>Alabama</li>
<li>California</li>
<li>Florida</li>
<li>Idaho</li>
<li>Kansas</li>
<li>Nevada</li>
<li>New York</li>
</ul>




Answer

Here's the jQuery code, place it at the bottom of your page:

(function(){
    function addClass(ul){
        ul.children('li.left').removeClass('left');
        ul.children('li.right').removeClass('right');

        $('ul > li:first-child').attr('class', 'left');
        $('ul > li:last-child').attr('class', 'right');

        var ulWidth = ul.width();
        var totalWidth = 0;

        ul.children('li').each(function () {
            totalWidth += ($(this).width() + 50);
            if (totalWidth > ulWidth) {
                $(this).addClass('left');
                $(this).prev().addClass('right');
                totalWidth = $(this).width();
            }
        });
    }

    var ul = $('ul.container');
    addClass(ul);

    $(window).on('resize', function(){
        addClass(ul);
    });
}());

Also the number 50 in the code is 'li' left and right padding and left and right border which adds up to 50. (15 + 15 + 10 + 10) Change it if needed.

Hope it helped!

Comments