3

Thanks for taking a look. I'm trying to used the jQ UI addClass / remove Class methods to expand an hr element upon clicking preceding sibling divs. jQ UI effects core enables smooth animated transition between two classes: http://jqueryui.com/demos/removeClass/. Additionally, hr must be added dynamically with $ to achieve the broader site design.

Here are the pieces of the puzzle:

  1. My code renders rows of four 100x100px sibling divs. These divs don't have classes, but FEEL FREE TO ADD THEM IF IT HELPS -- each div will eventually have a unique class. After every 4th div, there's a dynamically added hr.
  2. Upon clicking any given div, the immediate next hr must toggle to the class "open", which causes the row to expand. If this div is then clicked again, it must toggle/remove the class "open" from hr, causing the hr the shrink to it's original size.
  3. If one div is clicked to expand a hr and then another div is clicked, two animations must be triggered: first, the "open" class must be removed, causing the row to shrink back down, and THEN the class must be re-added to reopen the row. However, if, for example, a div is clicked to open the second row, and then a second div preceding the first hr is clicked, this action must first close the second hr and then open the second div's corresponding hr.

I'm stuck. I've tried a number of jQ function combos, but the results are whacky. What you see is the closest I've gotten. Thanks for giving this one a shot. Feel free to add to the code however you can to get this working.

<!--HTML...the children divs of ".main" can have their own unique classes if that helps-->
<div class="main">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

/*CSS-some of this creates other events not mentioned above. These are simplified versions of what I need for my final site design*/

.main  {
    width: 450px;
}
.main div {
    height: 100px;
    width: 100px;
    background-color: #000;
    margin: 3px;
    float:left;
}
div.select   {
    background-color: #f00;
    border: 2px solid #00F;
    margin: 3px;
    float:left;
    display: block;
}
div.active   {
    background-color: #f00;
    margin: 3px;
    float:left;
    display: block;
}
hr  {
    background-color: #FF0;
    float: left;
    display: block;
    height: 20px;
    width: 450px;
}
hr.open {
    float: left;
    display: block;
    height: 300px;
    width: 450px;

}

/*the JS - sorry about the double quotes.  I'm using Dreamweaver, which seems to add them to everything*/

$(document).ready(function() {
//dynamcally adds the <hr> after every 4th div.
    $(".main div:nth-child(4n)").after('<hr class="closed"></hr>');
//puts a blue border on the squares
    $('.main div').hover(function()  {
        $(this).addClass('select');
    },
    function() {
        $(this).removeClass('select')
    });
//changes the color of the active square to red and "deactivates" the previous one.
    $('.main div').click(function()  {
        $(this).toggleClass('active').siblings().removeClass('active');
    });
//here in lies the problem...???
    $('.main div').click(function()  {
        $('hr').removeClass('open', 1000);
        $(this).toggle
        (function() {
            $(this).nextAll("hr").first().addClass('open', 500);
        },
        function()  {
            $(this).nextAll("hr").first().removeClass('open', 500)
        });

    });
});
Earl1234
  • 37
  • 7
  • FYI, this is jQuery, not jQuery UI. jQuery UI is a collection of UI plugins like Autocomplete, Tabs, etc. – Barmar Sep 19 '12 at 07:34
  • 1
    hey, Barmar. Notice that addClass and removeClass argumuments include a duration component---this animates transition b/t classes and is only possible using the UI effects core. http://jqueryui.com/demos/toggleClass/. If i didn't require sequential animation to make this happen, my dilemma would be easily solvable. – Earl1234 Sep 19 '12 at 13:43
  • Have you tried using an element other than an HR? I realize using a plain div will jam up a lot of your other code; maybe try a span and style it to `display: block`. I really feel like styling HRs really isn't that well supported in many browsers and could easily be the root of your problem, but I have to admit, it's been a long time since I've looked at using HRs like that. – Patrick M Sep 19 '12 at 14:29
  • I created a jsfiddle of your stuff: http://jsfiddle.net/Bv57T/1/ Seems to be working reasonably well. There are some quirks about where you can and can't click. I'll try playing with it and see if I can get something smoother. – Patrick M Sep 19 '12 at 14:41

2 Answers2

2

I am pretty sure that this is what you want, I copied the general HTML layout from http://makr.com (you mentioned that that was what you wanted):

Demo: http://jsfiddle.net/SO_AMK/xm7Sk/

jQuery:

$(".main article:nth-child(4n)").after('<hr class="split"></hr>');
$(".main > article .slidedown").click(function(e) {
        e.stopPropagation();
}); // If you click on the slidedown, it won't collapse

var canAnimate = true,
    slideIsOpen = false,
    animateSpeed = 1000;

$(".main > article").hover(function() {
    $(this).addClass("hover");
}, function() {
    $(this).removeClass("hover");
}).click(function() {
    if (canAnimate) {
        canAnimate = false;
        var article = $(this),
            isThisOpen = article.hasClass("active");
        if (isThisOpen) {
            $(".main").queue(function () {
                hideSlide($(this))
            });
        }
        else {
            if (slideIsOpen) {
                $(".main").queue(function () {
                    hideSlide($(this));
                }).queue(function () {
                    positionPage(article, $(this));
                }).queue(function () {
                    showSlide(article, $(this));
                }).queue(function () {
                    positionPage(article, $(this));
                });
            }
            else {
                $(".main").queue(function () {
                    positionPage(article, $(this));
                }).queue(function () {
                    showSlide(article, $(this));
                }).queue(function () {
                    positionPage(article, $(this));
                });
            }
        }
    }
});

function showSlide(elm, main) {
        canAnimate = false;
        slideIsOpen = true;
        elm.nextAll("hr.split").first().addClass("active", animateSpeed);

        elm.children(".slidedown").css("top", (elm.offset().top + 114)).addClass("active").slideToggle(animateSpeed);

        elm.addClass("active");
        main.dequeue();
        canAnimate = true;
}

function hideSlide(main) {
        canAnimate = false;
        $(".main article.active").nextAll("hr.split.active").removeClass("active", animateSpeed);

        $(".main article.active").children(".slidedown").removeClass("active").slideToggle(animateSpeed);

        $(".main article.active").removeClass("active");
        $(main).dequeue();
        canAnimate = true;
        slideIsOpen = false;
}

function positionPage(elm, main) {
    canAnimate = false;
    var body;
    if ($.browser.safari) {
        body = $("body");
    }
    else {
        body = $("html");
    }
    var elmTop = elm.offset().top,
        bodyScroll = body.scrollTop();
    if (bodyScroll - elmTop == 0) {
        var speed = 0;
    }
    else {
        var speed = animateSpeed;
    }
    body.animate({
        scrollTop: elmTop
    }, speed, function () {
        main.dequeue();
        canAnimate = true;
    })
}​

This may seem like a large script for something so small but it has some fail-safes. The only bug is, if you start clicking quickly during transitions sometimes the queues end up in the wrong order. But, the average user doesn't click quickly during animations :D

A.M.K
  • 16,727
  • 4
  • 32
  • 64
  • A.M.K., this is brilliant! Thanks, man!! Now i'm gonna try to figure out what all of this means and does. Perfect. – Earl1234 Sep 20 '12 at 17:54
  • A.M.K., been messing around with this code. One thing, the rows need to be hidden until an article is clicked. The reason being that when the product line is filtered, all hr's are removed and then re-added. I did it with this snippet: $("article:visible:odd:odd").after('
    '); can't do it with nth-child as that also counts hidden elements. If hr.split isn't hidden initially, it causes a jerk when they're added dynamically. But I haven't been able to get your code fluid with hidden rows just yet. Pls let me know if you have an fixes.
    – Earl1234 Sep 21 '12 at 00:19
  • got it - it's as simple as messing w/the margin & elm.offset().top + xxx....thanks again!!! – Earl1234 Sep 21 '12 at 01:12
1

Try this on for size: http://jsfiddle.net/Bv57T/3/

Main changes:

  1. You had 2 .click bindings to the same selector $('.main div'). This is technically supported, I believe, but there's no reason for it and it makes your code a lot harder to follow.
  2. .toggle() doesn't take functions as parameters. Check the documentation for it; it's not like hover().
  3. There's no reason to have separate functions for the add and remove. You're also removing classes twice. Were you wanting the next HR to animate open and stay open? Or wanting it to open and close immediately? If the latter, there's no reason for this line $('hr').removeClass('open', 1000);. If the former, there's no reason for the second function() with $(this).nextAll("hr").first().removeClass('open', 500) in it.

Here's the javascript I used in the fiddle

$(document).ready(function() {
    //dynamcally adds the <hr> after every 4th div.
    $(".main div:nth-child(4n)").after('<hr class="closed"></hr>');
    //puts a blue border on the squares
    $('.main div').hover(
        function()  {
            $(this).addClass('select');
        },
        function() {
            $(this).removeClass('select')
    });
    //changes the color of the active square to red and "deactivates" the previous one.
    $('.main div').click(function()  {
        $('hr.open').removeClass('open', 1000);
        if(!$(this).hasClass('active')) {
           $(this).nextAll("hr").first().addClass('open', 500);
        }
        $(this).toggleClass('active').siblings().removeClass('active');
    });
});​

If that's not exactly what you want and can't figure it out from here, go ahead and post back and I can take another crack at it.

Edit New and improved version: http://jsfiddle.net/Bv57T/4/ Updated the js above as well.

It's still possible to fake it out if you click on a second div while an animation is ongoing. You could get around that by setting a (global) bool to true for the duration of an animation and checking it before starting the next animation.

But the root of the problem is that you're trying to have the state of the UI (DOM, in other words) double up as the state of the application. This can get really hairy with even simple operations (as well you've seen). My preferred approach for things like this is to use a library that separates the UI from the application. These are usually referred to as MVC (model-view-controller) or MVVM (model-view-viewmodel - a moniker I hate because it feels intentionally confusing). My favorite is knockout.js. It's fully compatible with jQuery and jQuery UI; check out this example: animated transitions.

There are more such libraries. Backbone.js is one, knockback.js combines knockout and backbone. I know I'm forgetting some other popular & good ones...

Patrick M
  • 10,547
  • 9
  • 68
  • 101
  • Thanks, Patick M. The problem is that when you click on the same div twice it SHOULD close the hr. As it is in your fiddle, clicking the same div twice first closes and then reopens the corresponding hr. That was my initial problem. Maybe there is something we can do with the class "active" of the div you're clicking on. When a div is clicked it's class becomes "active." So maybe clicking div.active will only close the hr while clicking any non "active" div will close any hr and then open the next?? not really sure how to implement this. Here's what I tried, but it's not behaving: – Earl1234 Sep 19 '12 at 15:48
  • $('.main div.active').click(function() { $('hr').removeClass('open', 250); }); $('.main div').not('.active').click(function() { $('hr').removeClass('open', 250); $(this).nextAll("hr").first().addClass('open', 1000); }); }); – Earl1234 Sep 19 '12 at 15:49
  • Ah, I understand now. Yeah, you will have to do some class inspection for jQuery to tell the difference. I expect the problem with your example bindings is that they're binding at the start when there isn't an active element. So you would have to rebind them after every event. Do-able, but I'll post back later today with some different ideas. – Patrick M Sep 19 '12 at 15:59
  • still same problem thought - clicking the same div twice fails to close the hr. – Earl1234 Sep 19 '12 at 16:00
  • you're the man. this project is stuck (at least in it's current mock up) until this problem gets solved. – Earl1234 Sep 19 '12 at 16:03
  • Edited with a modification. I think it does what you want more closely. peep it out and let me know. – Patrick M Sep 19 '12 at 16:54
  • That's a lot better. Ideally, the first hr would close before the second opens. Is there a way to do a callback that includes the IF statement to achieve this? I have a lot to learn -- been coding for 2wks. Really what I'm trying to do is build site similar to http://makr.com/. I dissected the moving parts in firebug. when you click on a product, a dynamically added hr below the product expands at the same time as a separate absolutely positioned div is overlayed... that engine is brilliant. Will i be able to design something like that more easily in one of the MVCs you mentioned? – Earl1234 Sep 19 '12 at 17:31
  • 1
    fyi, it looks like the site designer of makr used prototype for most of the code. – Earl1234 Sep 19 '12 at 17:33
  • 1
    `.toggle()` does have a form that takes function parameters, see http://api.jquery.com/toggle-event/ – Barmar Sep 19 '12 at 17:44