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>

2
  • 1
    After first click the toggleBool variable becomes a boolean variable in line toggleBool = !toggleBool;. So it's not supposed to work. Commented Oct 10, 2018 at 4:40
  • Please check stackoverflow.com/questions/40675821/… Commented Oct 10, 2018 at 4:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.