How to Change CSS on Button Click | SoloLearn: Learn to code for FREE!

0

How to Change CSS on Button Click

I have a div and a button. The div is styled by inline CSS to have a display of none. Whatever I try, however, I cant seem to use jQuery to change the display to inline-block when I click on the button. Thank you all for any answers!

7/6/2017 1:23:59 PM

Spoops

5 Answers

New Answer

+15

^~^ https://code.sololearn.com/WOEN2mEDVCEp/?ref=app

+10

Nice one @visph, your example might be shorter using the toggle method, no conditions and just one CSS class. ^^

+6

Another useful way to handle style through JS is to use 'className' property ('class' attribute in html tags) to set/unset some css classes: .show { display:inline-block; } .hide { display:none; } <div id="mydiv" class="hide">my div content</div> <input type="button" value="show/hide div" onclick="showhide('mydiv');"> <script> function showhide(target_id) { var target = document.getElementById(target_id); if (target.className=='show') target.className='hide'; else target.className='show'; } </script> Enough for this simple case, you must improve the condition to handle cases with many classes assigned to once element... Easiest way is to use the 'classList' property methods: if (target.classList.indexOf('show')!=-1) { target.classList.remove('show'); target.classList.add('hide'); } else { target.classList.remove('hide'); target.classList.add('show'); }

+4

@Maz: Yeah, you're right... I wasn't enough sure there was a toggle() method attached to the classList object, as I rarely use it (I was often forgotten for the classList property and commonly deal with className and regexp ;P Anyway, the code can be shorter, as you need only one class ('hide' or 'show'), and define a default behaviour for the other state ^^ However, this was a bit verbose for learning purpose ;)

+1

Thank you so much Maz, that makes it very clear!