I partied with my web browsers!

I just moved to SF just over a two weeks ago, and don’t have any friends! Oh so lonely — who will party with me? Well, since I’ve been hanging out a lot with my web browsers recently, why not invite them to party!

partyMarc

hmmm, who to invite?

I wrote a little script with recursion, and bam instant party!

Click here to party: 

Drag this Link to your bookmark bar for future party use! It will turn ANY SITE into a party!

Lets dive into the code: It’ll be hard to read the code while partying, so refresh your browser

Line 1:  
var partyTime = function(domElement) {
This creates a function that accepts a domElement.  The domElement we pass in is “document.body”

Line 2: 
if (domElement.tagName === "DIV")
looks at whether the current domElement has a tagName of “DIV”.  Examples of tag names are: <A> or <IMG>

Line 3: 
domElement.style.background = "#" + Math.random().toString(16).slice(2, 8)
Sets that current Dom Element background to a random colour.

Line 6: 
var domChildren = domElement.children
Grabs all the of the children of the current domElement and places them in a variable.

Lines 8 – 10: 

Because the children of a DOM tree is an array format.  We iterate through the array for each element and then run the partyTime function for each node.


Note on recursion:

Typically recursive functions need a basecase to know when to exit.   But this recursive function has a natural exit point.

At some point the DOM element selected will not have any children and set the domChildren to an empty array, thus domChildren.length // equal to 0 and it will skip over the for loop on line 8 and start heading back up the call stack.

It keeps repeating this process until it’s checked over every element within the document.body and changed all the
div’s to a new “party” colour.


Line 13:
setInterval(partyTime.bind(this,document.body),150)
In order to make this party, we call the setInterval to repeat every 150 milliseconds.   We MUST bind the function because we are passing in an argument.  If we don’t, partyTime will execute immediately and not get passed into the setInterval function.

Lines 14 – 17:

Creates a variable to an .mp3 link I uploaded.  We then create an <Audio> element and assign it to an ‘audio’ variable.  Set the audio source to the mp3 and then append it to the DOM.

Line 18:
audio.play();
Play the audio and PARTY-TIME!


Lastly I used a tool called “Bookmarkleter” to convert my javascript into a bookmarket.


Now that I had the bookmarklet ready to go, my web browsers and I partied for 4+ hours until FireFox reverted back to his natural pyromaniac ways and set my apartment ablaze.

partyMarc2

oh FireFox, you so crazy!

The fire department came 3 hours later.

Share: Share on Google+Share on FacebookTweet about this on TwitterShare on RedditBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *