Can I run CSS commands in javascript? HTML

Asked

Viewed 781 times

3

It is possible to execute CSS commands in javascript?

For example, if I clicked on a button, its color would change?

2 answers

5


Of course, pretty much everything that happens in GIFT can control/manipulate with javascript:

var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
    this.style.backgroundColor = 'green';
})
#btn {
   background-color: red; 
}
<button id="btn">CLICA AQUI</button>

May delegate the html event, in this case is the onclick which is the syntax of the click event as an html attribute:

function change_color(ele) {
    ele.style.backgroundColor = 'green'; 
}
button {
   background-color: red; 
}
<button onclick="change_color(this);">CLICA AQUI</button>
<button onclick="change_color(this);">CLICA AQUI</button>
<button onclick="change_color(this);">CLICA AQUI</button>

Or, often this is my preference, we can add/remove the classes that style the elements:

var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
    var btn = document.getElementById("btn");
    if(btn.classList.contains('green')) {
       btn.className = "";
       return;
    }
    btn.className = "green";
})
button {
   background-color: red; 
}
.green {
  background-color: green;
}
<button id="btn">CLICA AQUI</button>

In these cases the only element/attribute manipulated is the button/background color.

These are simple, basic examples that can give you an idea of the possibilities (everything you do in css can do in js, and more).

-1

With these features, is it possible to then control menu and submenus items, created with UL and LI, properly identified by classes? If you want to attach a small example, I would be grateful, I am beginner in the area.

Thank you.

  • Vitor and Miguel, first of all I apologize for the delay in responding, I ended up taking some time in my learning and forgot that I had posted here. Thanks for the help, I’m restarting studies and the tips that posted will be my starting point.

Browser other questions tagged

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