Setting var in jQuery function

Hi,

Im working with Javascript for the first time and am having a problem setting a javascript var on a jQuery onclick function. Can anyone see why the var in document.write(num_cow); is not being set?

Thanks


<script>var num_cow;
</script>

<div class="green_button_1_class_1 ">ADD TO YOUR FARM</div>

<script>		
	
			document.write(num_cow);
	
		</script>

<script>
$(document).ready(function() {

$('.green_button_1_class_1').click(function() {
			
			// increment the Cow variable
			num_cow = num_cow + 1;
			
    		return false;
  		});
}
</script>



Yes, you are writing the num_cow variable to the page on page load, at the time of page load, num_cow is undefined (your top line), it isn’t truly defined until the div is clicked.

Instead you likely want to do this


 <script>var num_cow = 0;</script>

<div class="green_button_1_class_1 ">ADD TO YOUR FARM</div>
<div id="itemsForFarm"></div>

<script>
$(document).ready(function() {
     $('.green_button_1_class_1').click(function() {
            // increment the Cow variable
            num_cow = num_cow + 1;
            $('#itemsForFarm').text(num_cow);
            return false;
     });
});
</script>

Brilliant! That’s sorted it.