I'm having issues with having a function execute with the click event handler. If I get rid of the function numberCheck() and post the code directly into the event handler, then it works fine. Am I missing something basic here?
Here is my code:
jQuery(document).ready(function(){
var scopedVariable;
var number = Math.floor(Math.random()*11);
function numberCheck() {
$(this).closest('#outsideContainer').find('.hotter').addClass('hideStuff');
$(this).closest('#outsideContainer').find('.colder').addClass('hideStuff');
var guess = $(this).closest('#guessContainer').find('.value').val();
if( +guess === number)
{
$(this).closest('#outsideContainer').find('.gotIt').removeClass('hideStuff');
}
else {
$(this).closest('#guessContainer').find('.value').val('Please guess again');
if(Math.abs(guess - number) < Math.abs(scopedVariable - number)) {
$(this).closest('#outsideContainer').find('.hotter').removeClass('hideStuff');
}
else if(Math.abs(guess - number) > Math.abs(scopedVariable - number)) {
$(this).closest('#outsideContainer').find('.colder').removeClass('hideStuff');
}
scopedVariable = guess;
}
}
$('.query').on('click', function() {
numberCheck();
});
});
here is my HTML if needed:
<body>
<div id="outsideContainer">
<div id="guessContainer">
<h3> Guess a number between 1 and 10 </h3>
<input id="txtfield" name="txtfield" type="text" class="value"/><br>
<input type = "submit" class="query" />
</div>
<div id="guessShow">
<p class="hotter hideStuff" > Getting Hotter!! </p>
<p class="colder hideStuff"> Getting Colder, BRRR!!! </p>
<p class="gotIt hideStuff"> Awesome! You have guessed the number </p>
</div>
</div>
</body>
Any help for this is much appreciated.
Try passing this to your function (numberCheck(this)) and then name the parameter in your function something else and change the instances of this in the function to that name, like so:
function numberCheck(submitButton) {
$(submitButton).closest('#outsideContainer').find('.hotter').addClass('hideStuff');
[...]
}
$('.query').on('click', function() {
numberCheck(this);
});
Instead of executing the function, pass that function as an input parameter to the event click.
$('.query').on('click',numberCheck);
On this way, you are passing the callBack as a input parameter, and your function gets access to the object, where the event click was fired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With