Search code examples
javascripthtmlfor-loopfor-in-loop

Loop thru object to output icons javascript


Sorry for the poor title–I didn't know what to put. Anyways, I have this object I want to loop thru in order to dynamically output some icons onclick:

<button id="btn">hit me</button>
var socialMedia = {
    facebook: "http://facebook.com",
    twitter: "http://twitter.com",
    instagram: "http://instagram.com",
    dribbble: "http://dribbble.com",
    social: function() {
        var output = "<ul>";
        var myList = document.querySelectorAll('.socialSpot');

        for (var key in arguments[0]) {
            output += '<li><a href="' + this[key] + '"><img src="_assets/' 
                   + key + '.png" alt="' + key + 'icon"></a></li>';
        }

        output += '</ul>';

        for (var i = myList.length - 1; i >= 0; i--) {
            myList[i].innerHTML = output;
        };
    }
};

var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
    socialMedia.social(socialMedia);
}, false);

I know I could remove the method and instantiate it while passing the object, but I was wondering how I could go about it this way. In other words, I want to leave the function as a method of the socialMedia {}. Any pointers?


Solution

  • Just add a if (typeof obj[key] != "string") continue; test to your loop:

    …
    social: function(obj) {
        var output = "<ul>";
        var myList = document.querySelectorAll('.socialSpot');
    
        for (var key in obj) {
            if (typeof this[key] != "string") continue;
            output += '<li><a href="' + this[key] + '"><img src="_assets/' 
                   + key + '.png" alt="' + key + 'icon"></a></li>';
        }
    
        output += '</ul>';
    
        for (var i = myList.length - 1; i >= 0; i--) {
            myList[i].innerHTML = output;
        };
    }
    

    Of course, simply using another object would be so much cleaner:

    var socialMedia = {
        data: {
            facebook: "http://facebook.com",
            twitter: "http://twitter.com",
            instagram: "http://instagram.com",
            dribbble: "http://dribbble.com"
        },
        social: function(obj) {
            var data = obj || this.data;
    
            var output = "<ul>";
            for (var key in data) {
                output += '<li><a href="' + data[key] + '"><img src="_assets/' 
                       + key + '.png" alt="' + key + 'icon"></a></li>';
            }
            output += '</ul>';
    
            var myList = document.querySelectorAll('.socialSpot');
            for (var i = myList.length - 1; i >= 0; i--) {
                myList[i].innerHTML = output;
            };
        }
    };
    
    var theBtn = document.getElementById('btn');
    theBtn.addEventListener('click', function() {
        socialMedia.social();
    }, false);