BenM
BenM

Reputation: 53198

Detect colliding elements in jQuery

I am currently working on creating an application similar to the Contacts app on iOS. The style and so forth really isn't important right now, but I would like to get the functionality working.

I have set up a jsFiddle to show what I'm trying to achieve (http://jsfiddle.net/hpQVy/), and here's the code:

HTML:

<ul class="divided">
    <li class="divider">A</li>
    <li>Andrew Acheson</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li>Luke Ayre</li>
    <li class="divider">B</li>
    <li class="divider">C</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
    <li>Charlie Sheen</li>
</ul>

JavaScript:

$(function() {
    // First off, dock the first one:
    $('ul.divided li.divider').eq(0).css({ position: 'fixed' });
    $(window).scroll(function() {

        //

    });
});

CSS:

body {
    padding: 0;
    margin: 0;
}
ul {
    list-style: none;
    padding: 0;
    margin: 0;
    font-family: Arial;
}
    ul li {
        padding: 10px;
        border-bottom: 1px solid #000;
        width: 100%;
        box-sizing: border-box;
    }
        ul li.divider {
            font-weight: bold;
            padding: 2px 10px;
            background-color: #aaa;
            color: #fff;
            text-shadow: 0 1px 0 #000;
            opacity: 0.7;
        }

What I would like to do is simulate the 'docking' of the list dividers. My train of thought is to detect when any divider collides with the one that is docked, and then animate and dock that one accordingly. My question I suppose is what is the best way to detect when a list divider (li.divider) collides with the li.divider that has the position: fixed. I need to detect collisions both from the top, and bottom (if that makes sense).

Can anyone recommend a way of detecting when the li elements might collide?

Upvotes: 0

Views: 446

Answers (1)

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

ok maybe this isn't the answer you were looking for, but have a look at this plugin. I think it's just what you are trying to create

Upvotes: 1

Related Questions