javascript - Button Only Works on Second Click After Reload -


i'm creating board tiles can clicked change colors. have "clear board" button clears board tiles white again, reason button works on second click after each page reload. i've tried wrapping javascript in document ready function didn't help. how can work on first click after reload?

html:

<h1 class="title">wacky painter</h1>     <div class="easel">     </div>     <form class="clear_board">         <button type="button" id="clear_button" class="btn" onclick="clearboard()">clear board</button>     </form> 

css:

body {   font-family: sans-serif;   color: #ff757a; }  .easel {   width: 300px;   outline: #c8c8c8 5px solid;   margin: 0 auto; }  .square {   width: 20px;   height: 20px;   outline: thin solid #c8c8c8;   display: inline-block;   margin-top:-2px; }  form {   margin: 10px auto; }  .title {   margin: 0 auto;   text-align: center;   padding-bottom: 20px; } 

javascript (with jquery):

window.setupeasel = function() {     var squarestring = "";     for(var i=0; < 195; i++) {         squarestring+='<div class="square"></div>';     }     $('.easel').append(squarestring) }  window.givecolor = function() {     $('.easel').on('click', '.square', function() {         var letters = '0123456789abcdef'.split('');         var randomcolor = '#';         (var = 0; < 6; i++ ) {             randomcolor += letters[math.round(math.random() * 15)];         }         $($(this)).css('background-color', randomcolor);     }) } window.clearboard = function() {     $('#clear_button').on('click', function () {         $('.square').css('background-color', 'white');     }) }      $(function () {         setupeasel();         givecolor();     }); 

here's working jsfiddle: http://jsfiddle.net/michelleglauser/yz6mdx1f/1/

you don't set jquery click event handler on clear button until click on button (using event handler assigned in button attributes). try instead:

// code above stays same  // adjust merely responsible clearing background window.clearboard = function() {     $('.square').css('background-color', 'white'); };  $(function() {     setupeasel();     givecolor();      // assign click handler on dom-ready     $('#clear_button').on('click', function () {         clearboard();     }); }); 

and finally, remove inline onclick attribute button markup.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -