MarcusSparks4 MarcusSparks4 - 1 month ago 6
Javascript Question

How to run function after event is run?

I am a beginner with all coding. Here is my general goal. I am running something relatively simple where I have 8 superheroes on the screen. I would like the user to eliminate the 4 DC superheroes from the screen and after all 4 of them are eliminated from the screen I want the system to alert the user that they have won the game. They don't have to do it in any order so I ran the superHero function each time a DC character was clicked to check if all four DC superheroes had been eliminated yet. Somebody please help me. I feel like it is something very simple I am messing up on. Thanks a ton in advance.

/*This is my jquery that shows all 8 of my superheroes*/
$('#heroes').show();
var flashHidden = !$('#greenlantern').is(':visible');
var greenHidden = !$('#greenlantern').is(':visible');
var batmanHidden = !$('#batman').is(':visible');
var supermanHidden = !$('#superman').is(':visible');
function superHero() {
if(flashHidden && batmanHidden && supermanHidden && greenHidden) {
alert ("Congratulations!!! You have won the game!! Please proceed forward and fill out a quick survey for the developers");
}
}
$('#flash').click(function(){
$('#flash').hide('slow',function(){
superHero();
});
});
$('#greenlantern').click(function(){
$('#greenlantern').hide('slow',function(){
superHero();
});
});
$('#batman').click(function(){
$('#batman').hide('slow',function(){
superHero();
});
});
$('#superman').click(function(){
$('#superman').hide('slow',function(){
superHero();
});
});
});


Right now the current thing that is happening is I will eliminate all of the correct superheroes and it will not alert me that the user has won. I've tried a lot of different things and the only other result I've gotten is to have the system alert the user every time they click on a superhero that they've won which is also incorrect.

EDIT

This has been solved by changing the scope of the variables to inside the function.

Answer

You should declare your variables i.e. flashHidden in your function. Currently you are setting then at the start.

function superHero() {
    var flashHidden = !$('#flash').is(':visible');
    var greenHidden = !$('#greenlantern').is(':visible');
    var batmanHidden = !$('#batman').is(':visible');
    var supermanHidden = !$('#superman').is(':visible'); 
    if(flashHidden && batmanHidden && supermanHidden && greenHidden) {
        alert ("Congratulations!!! You have won the game!! Please proceed forward and fill out a quick survey for the developers");
    }
}

Additionally your click handler can be condensed into

$('#flash, #greenlantern, #batman, #superman').click(function(){
    $(this).hide('slow',function(){
        superHero();
    });
});