Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of years:

$years = [1952,1954,1961,1962,1965,1982,1984,1984,1984,1985,1986,1986,1987,1988,1990,1991,1991,1993,1995]

I'm creating a timeline and my timeline uses 10 years of ranges, so it looks like this:

       1950      1960      1970      1980
.........|.........|.........|.........|.........

With the help of the jQuery each function i loop through these years and i display them on the timeline by creating a div and i position them using the left css attribute (1 year is 22px):

$.each(years, function(key, value) { 
    var event = $('<div>').addClass('event');
    var posX = value*21;

    event = event.html(value).css('left',posX+'px');

    $('#timeline').append(event);
});

So far so good, but us you can see i have lots of years and i can't display them correctly.

If in a 10 year range theres more than 3 events, i want to display a button instead of the event div and when i click on it i can use a popup to show the rest of the events.

How can i achieve this?

share|improve this question
    
It would be easier if your data was formatted better, each year should be unique, and the events should be inside the year. Eg: {1952: ['event'], 1984: ['event1', 'event2']} –  Christian Varga Dec 23 '12 at 17:48
    
It looks like that, i just simplified it for the question –  passatgt Dec 23 '12 at 17:49
    
In that case, update the code to reflect the actual data you're using. In order to help you with a solution that works for you, we'll need to see the actual structure you're using. –  Christian Varga Dec 23 '12 at 17:52
    
Oh ok, i see what you mean. Its coming from the server and i can't change that, so i have to make it work with this. –  passatgt Dec 23 '12 at 17:52

1 Answer 1

up vote 3 down vote accepted

It would be easier to work with years in their associated decades. I would create a decades array and populate it like the following:

var $years = [1952,1954,1961,1962,1965,1982,1984,1984,1984,1985,1986,1986,1987,1988,1990,1991,1991,1993,1995];

var decades = [];
for(var i=0; i<$years.length; i++)
{
    var year = $years[i];
    var decade = (Math.floor(year / 10) * 10);
    if(!decades[decade])
        decades[decade] = [];
    decades[decade].push(year);
}

for(decade in decades){
    var years = decades[decade];
    // decade will be 1950, 1960, 1980, etc.
    // years will be an array of years within that decade

    if(years.length > 3) {
        // ...
    } else {
        // ...
    }
}
​
share|improve this answer
    
+1 was working on virtually same solution –  charlietfl Dec 23 '12 at 17:55
    
great solution, thank! –  passatgt Dec 23 '12 at 18:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.