Is it possible to execute CSS commands in javascript? HTML

3

Is it possible to execute CSS commands in javascript?

Example, if I clicked a button, would its color change?

    
asked by anonymous 16.08.2016 / 18:47

2 answers

5

Of course, virtually everything that happens in the DOM 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>

You can delegate the event in html , in which case it is the onclick which is the click event syntax as 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, many times 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 background button / color.

    
16.08.2016 / 18:57
-1

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

Thank you.

    
25.05.2018 / 01:10