Sebastian
Sebastian

Reputation: 55

Can I style text within a JS object?

For example I have this object:

function getBadgeContent() {
    let os = detectOS();
    let obj = {};

    if( os == "android" ) {
        obj = {
            src: "----",
            href: "---",
            info: "Download app for Android"
        };
    } else if( os == "iOS" ) {
        obj = {
            src: "---",
            href: "---",
            info: "Download App for iOS"
        };
    } else {
        obj = {
            src: "---",
            href: "----",
            info: "Download App for Windows"
        };
    return obj;

}

    }

This object is then called (not sure if this is the correct term). And a different badge is displayed in an HTML page depending on the device the user is on.

function buildBadge() {
    let obj = getBadgeContent();
    let html = '';

    if( obj ) {
        html = obj.info + '<a target="_blank" href="'+ obj.href+'"><img src="' + obj.src + '" alt="store_badge" /></a>';
    }

    return html;

}

I want to give info specific styling. Basically I want the text to display above the badge and say "Download for your specific device".

As a bonus, I would like to give each badge styling rules so that they are all the same height and width. But that can be done outside of code.

Thank you!

Upvotes: 0

Views: 317

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

You can probably shorten your functions quite a bit by cutting out the repetitions.

And, as you can see in my little demo, do all the formatting in CSS.

function addBadge(ev){
 let OO={android:['androidforums','href4android.html','android'],
     iOS:['apple','iOS_href.html','iOS'],
     win10:['microsoft','win10_href.html','windows']};
 var o=OO[detectOS()]||OO.win10;
 document.getElementById('main').innerHTML+='<div class="badge">Download app for '+o[2]
   +'<br><a href="'+o[1]+'"><img src="//logo.clearbit.com/'+o[0]+'.com"></a></div>';
}
var i=0;
function detectOS(){ // dummy function
  return ['android','iOS'][i++%3];    
}

document.getElementById('add').addEventListener('click',addBadge)
.badge {display:inline-block; height:80px;width:200px;
    background-color:#ccc;
    text-align:center; margin:6px}
.badge img {height:32px;}
<button id="add">add</button>
<div id="main"></div>

Upvotes: 1

Troy Bailey
Troy Bailey

Reputation: 153

You can add styling to the 'a'(anchor) element with a style attribute <a style="height: 100px"></a> for example and just add the css that goes in the style attribute as a new property to your json object.

Upvotes: 1

Related Questions