javascript - Create a button that changes between red and green -
i want create simple button changes between colors red , green click them indicate has been completed. know of simple way button change , forth between colors? setup of page isn't how want yet button needs configured before can format rest of page how like. left out css deals body , other things headings. here have far after looking online while:
function colorchange(id) { var e1 = document.getelementbyid(id); var currentclass = el.getattribute("class"); if(currentclass == 'classa') { el.setattribute("class", "classb"); } else { el.setattribute("class", "classa"); } }
#select { width: 10em; height: 1.5em; } .classa { background: red; } .classb { background: green; }
<input type="button" id="select" onclick="colorchange('select')" class="classa" />
here native javascript version. first query button directly getelementbyid
selector. add event listener, waiting click event.
the classlist
, although returns array, can't use indexof
on it. however, can use contains
it. it's important note classlist not available in internet explorer 9 or earlier versions
var button = document.getelementbyid('my-button'); button.addeventlistener('click', function() { if (button.classlist.contains('red')) { button.classlist.remove('red'); button.classlist.add('green'); button.innerhtml = 'done'; } else { button.classlist.remove('green'); button.classlist.add('red'); button.innerhtml = 'not done'; } });
.green { background: green; } .red { background: red; }
<button id='my-button' class='green'>change color</button>
this best accomplished through jquery , it's toggleclass
function.
$('#my-button').on('click', function() { $(this).text($(this).hasclass('red') ? 'done': 'not done'); $(this).toggleclass('red'); $(this).toggleclass('green'); });
.red { background: red; } .green { background: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='my-button' class='red'>change color</button>
as can see above, it's easier in jquery.
Comments
Post a Comment