Styling Elements with Function (Javascript)

Asked

Viewed 137 times

0

I’m creating a javascript exercise, my idea was to create a function that would give me as return an icon, I’m using the Fontawesome for this. I managed to make him show the icon and the message but wanted to add styles preset by me for titles, emphasis .. etc, by means of a function but still could not think of a form. I even tried to use Swith but it just copied css as any string

function icones(ico_nome, texto,style ){ // Captura o nome do icone, o estilo que sera utilizado e o texto
    switch(ico_nome) { //Verifica o icone do argumento
        case 'user':
            ico_nome = '%c ' //Icone, só sera visualizado após a declaração CSS
            font = 'font-family: "Font Awesome 5 Free"; font-weight: 900; font-size: 20px; content: "\f434";'
        break
    }  
    switch(style) { //Estilizando texto
        case 'titulo':
            texto = 'color: red'
        break
    }
    console.log(ico_nome,font,texto) 
}
icones('user','usuario', 'titulo') //Aplicando valores a função

  • I don’t understand the question. You want to apply CSS in the console text? If that’s the question the answer is impossible to do that. What you can do is create an element with createElement() adjust its properties and then insert into the DOM to be rendered on the HTML page itself.

  • 1

    It is not impossible kk, you can yes add CSS, for this just add "%c Before the output message in my case would go console.log(" %c Hello world", "color:red), will not be possible in a terminal but in Crome console can run.

  • It didn’t work! https://imgur.com/a/cWabOCM. Thanks man I didn’t know that!

  • 1

    Living and learning kkkkk happy new year

1 answer

1

After several attempts and errors, I achieved the feat without using the DOM, the "secret" was to add 2 styles to the same method (console.log)

function icones(ico_nome,texto,style ){ // Captura o nome do icone, o estilo que sera utilizado e o texto
    switch(ico_nome) { // Check argument icon
        case 'user':
            ico_nome = '%c ' // Icon will only be displayed after CSS declaration
            font_icon = 'font-family:"Font Awesome 5 Free"; font-weight: 900; font-size: 20px;' //Declara a fonte para visualização
        break
    }  
    switch(style) { // Styling text
        case 'titulo': // Set styles for titles
            font_icon += 'color:red;' //Set the color Red to Icon
            style_text = 'color:blue; font-family: Arial;' // Set styles for texts
        break
        default: 
            font_icon += 'color: black' // Set default color
    }
    console.log(ico_nome + ' ' + '%c' + texto,font_icon,style_text)  //Join the 2 styles and reveal the output
}
icones('user','Usuario', 'titulo') //Applying values to function

Saida console

Browser other questions tagged

You are not signed in. Login or sign up in order to post.