Tuesday, November 11, 2014

Get the zodiac sign for a date in JavaScript

Just like the title says,

I was building a new layout for our data view plus web part that shows upcoming birthdays from a SharePoint list.

I wanted to show the zodiac sign for each person, using HTML codes you can render the signs but the hard part was to figure out the correct sign for each date.

Here is the end result:


You can get this layout and the javascript free from our web site (should be posted soon), but here is what I did in a nutshell (stay with me, its not short):

1. I created an object that has all the start dates for each sign, with the HTML sign for it and its name (for tooltip):

var zodiacSigns = {
    120: {html: "&#9809",text: 'Capricorn'},
    218: {html: "&#9810",text: 'Aquarius'},
    320: {html: "&#9811",text: 'Pisces'},
    420: {html: "&#9800",text: 'Aries'},
    521: {html: "&#9801",text: 'Taurus'},
    621: {html: "&#9802",text: 'Gemini'},
    722: {html: "&#9803",text: 'Cancer'},
    823: {html: "&#9804",text: 'Leo'},
    923: {html: "&#9805",text: 'Virgo'},
    1023: {html: "&#9806",text: 'Libra'},
    1122: {html: "&#9807",text: 'Scorpius'},
    1222: {html: "&#9808",text: 'Sagittarius'},
    1231: {html: "&#9809",text: 'Capricorn'}

2. Now, for each date I have I build a number from the month+day, next I loop through all elements of zodiacSigns until I get a value greater than the current date – which means the one before was the correct sign. Then I build the html span with that info:

var zodiacValue = parseInt(monthStr + dayStr, 10);
var currentZodiacSign = null;
for (var z in zodiacSigns) {
    try {
        if (currentZodiacSign == null) currentZodiacSign = zodiacSigns[z];
        if (zodiacValue > parseInt(z,10))
            currentZodiacSign = zodiacSigns[z];
        else break;//passed the date - the last one was the right sign. stop looping.
    catch (e) {
var zodiacPart = "";
if (currentZodiacSign != null)
    zodiacPart = "<span class='ZodiacSign' title='" + currentZodiacSign.text + "'>" + currentZodiacSign.html + "</span>";

A lot of work, but I like the result.

No comments: