0

I have a variable named toggleBool and function named toggleBool in the following jQuery script.

It works except variable toggleBool doesn't alter between true and false with each button click that calls toggleBool(). If I change the variable name to e.g. toggleBoolean, then everything works. Also, I'm using alert() to trace. Is there a tool that allows me to insert breakpoints in jQuery or javascript?

     toggleBool = false;
     iter_n = 0;
     jQuery('#pResult').css(
      { 'font-size'  : '20px',
       'background-color' : "#fff8dc" ,
      })
     $('#clickMe').css(
      { "background-color" : "#e9ffdb", 
       "font-size"  : "30px",
       "font-family"  : "Courier",
       "font-style"  : "italic",
      })
     jQuery('#clickMe').click(function()
     {
      toggleBool();
      if (toggleBool == true)
       $('#fColor').css('color', 'magenta');
      else
       $('#fColor').css('color', 'blue');
      $('#pResult').html('You just clicked the event button ' + iter_n + '-th time!')
      function toggleBool()
      {
       iter_n++;
       toggleBool = !toggleBool;
      }
     })
     
     <button id='clickMe'>Click the button to toggle color</button>
     <h2 align=center>
     <p>There are so many <span id='fColor' style="color:blue">colorful</span> flowers.</p>
     </h2>
     <p align=center id='pResult'> This is the default paragraph before click event. </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
Leon Chang
  • 669
  • 8
  • 12
  • 1
    After first `click` the `toggleBool ` variable becomes a boolean variable in line `toggleBool = !toggleBool;`. So it's not supposed to work. – subhasis Oct 10 '18 at 04:40
  • Please check https://stackoverflow.com/questions/40675821/what-happens-when-javascript-variable-name-and-function-name-is-the-same – saAction Oct 10 '18 at 04:48

1 Answers1

0

To debug hit F12 in Chrome and the debug window opens.

Put a break point on the line

iter_n = 0;

and type toggleBool in the console and you will see a boolean value be printed out.

Then put a breakpoint inside the clickme function on the line

if (toggleBool == true)

and type toggleBool in the console and you will see a function be printed out.

You need to understand scope of variable and that toggleBool changes scope from being a global variable outside the function and a function once you are inside the clickme function.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60