In short, your if
logic is running as soon as the DOM is ready (which is before the user gets a chance to click your button) because you've placed it directly inside of JQuery's document.ready callback function:
$(document).ready(function(){
// Anything here will execute one time, when the DOM is fully parsed
});
In order for that if
logic to be run at some point after the button is clicked, it will need to be placed into a function that can be called whenever you want it to be:
function testButton(){
if (bar){
console.log("At entrance");
$("#line1").html("Go into cave?");
$("#btn1").html("Yes!!");
} else{
console.log("I am error");
}
}
But, the real question is when should this function run? It doesn't make sense for it to run right after the button is clicked because in the click
event handler for the button, the bar
variable is manually set to 1
. If you call your testing function right after the click, it will always enter the true
branch of your test.
If you're looking to find a way to keep track of places the player has been, a better approach would be to set up an array of those places and check the array as the user moves around.
So, in the end, you'll want to set up your code like the following:
var visitedPlaces = []; // Store visited places here
$(document).ready(function(){
// When any of the location change buttons get clicked...
$(".changeLocation").click(function(){
// Extract the location from the data-* attribute of the clicked button
var newLocation = $(this).data("location");
// Test to see if player has already gone here
if (testLocation(newLocation)){
console.log("You've already been to the " + newLocation + "!");
} else {
console.log("Entering " + newLocation + "!");
}
visitedPlaces.push(newLocation); // Record that player has been to cave
});
});
// Call this function anytime you need to test the bar variable:
function testLocation(loc){
// Check if the location is already in the array and return true/false as appropriate
return (visitedPlaces.indexOf(loc) > -1) ? true : false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id = "line1"> You are in a field </p>
<!-- Use data-* attributes to signal where the user is going -->
<button class="changeLocation" data-location="cave">[ Go to cave ]</button>
<button class="changeLocation" data-location="inn">[ Go to inn ]</button>
<button class="changeLocation" data-location="mountains">[ Go to mountains ]</button>