HackMIT This Weekend!

HackMIT is this weekend, September 16-17.

I’m happy to announce that I’ll be mentoring as one of the local Microsoft MVPs that were invited to help as part of the Microsoft sponsorship of the event. I look forward to building some incredible applications with some of the brightest students coming to Cambridge, and may the best faction win! Keep an eye out for me Sunday morning, and feel free to reach out if you’re attending.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

 

 

Advertisements

Generating Unique Ids on the Fly

Let’s do some JavaScript!

This post may be a little off-topic from my normal content, although it isn’t Xamarin, it could be used for hybrid frameworks like Ionic or base Cordova.

What we’re going to do is look at ways to generate unique ids on the fly for anchor tags. This could be used to help with your Google analytics or general user interaction tracking.

First thing we need is a function to generate the ids:


var lastId = 0;
function uniqueId(prefix){
    lastId++;
    return prefix+lastId;
}

Now what we need to do is use this function to set the ids on all our anchors:


document.addEventListener("DOMContentLoaded", function(event) {
    var anchors = document.getElementsByTagName("a")
    for(var i = 0; i < anchors.length; i++){
        anchors[i].id = uniqueId("generatedId");
    }
});

Doing it this way ensures that our ids are the same each time we load the page since it is based on their position when the DOM is loaded. This set up isn’t fool proof, obviously. If your page’s content is inconsistent, tags could end up with different ids than they had before. Some of these problems can be handled better by using a smarter prefix for your id.