How to use JavaScript to Alter CSS for Multiple Elements -
i trying use javascript change background color of element after being selected, , make sure 1 element @ time has particular background color. once user selects on different element previous element selected replaced different background color. able toggle individual elements selecting on each element. need able select on element , apply new background color, have javascript change background color of active element different color (one less click).
what trying similar modern navbars or list items 1 element @ time “active” , has background color different other elements in same div, row, etc.
notes work utilizing bootstrap , have no desire use jquery particular project.
css:
<!doctype html> <html lang="en"> <head> <style> h4 { border: 1px solid black; border-radius: 8px; padding: 10px 2px 10px 2px; margin: 20px 20px 0px 20px; background-color: #f0f0f0; border-color: #f8f8f8; color: #505050; cursor: pointer; } .active { background-color: #99e6ff; } </style> </head> </html>
html:
<div id="ptworowone"> <div class="row"> <div class="col-md-4 row row-centered"> <h4 id="techbio" class="test">biology</h4> </div> <div class="col-md-4 row row-centered"> <h4 id="techcart" class="test">cartography</h4> </div> <div class="col-md-4 row row-centered"> <h4 id="techchem" class="test">chemistry</h4> </div> </div> </div>
javascript:
document.getelementbyid("techbio").onclick=function() { document.getelementbyid("techbio").classlist.toggle('active'); } document.getelementbyid("techcart").onclick=function() { document.getelementbyid("techcart").classlist.toggle('active'); } document.getelementbyid("techchem").onclick=function() { document.getelementbyid("techchem").classlist.toggle('active'); }
an example can seen here: http://jsbin.com/fugogarove/1/edit?html,css,js,output
if clarification needed let me know.
another similar yet simpler way it: jsbin ;)
var h4 = document.getelementsbyclassname("test"), act; [].foreach.call(h4, function(el){ el.addeventlistener("click", function(){ if(act) act.classlist.remove("active"); return (this.classlist.toggle("active"), act=this); }); });
Comments
Post a Comment