jQuery function questions

I'm getting some interesting results with my jQuery function. The code I am running looks like this:

$(document).ready(function(){      //Fade menu when play is pressed
    $('input').click(function(){
       $('menu').fadeOut(1000);
    });
});

And it's used in my HTML like this:

<!DOCTYPE html>
<html>
    <head>
        <script src='three.min.js'></script>
        <script src='cannon.min.js'></script>
        <script src='jquery2.2.2.min.js'></script>
        <script src='game.js'></script>
        <script src='jquery.js'></script>
        <title>really beta game lmaoo</title>
        <meta charset="utf-8">
        <style>
            body {
                background-image:url('Images/backgroundImg.jpg');
                background-repeat:no-repeat;
                background-size:cover;
            }
            input {
                position:absolute;
                bottom:21%;
                right:40%;
            }
        </style>
    </head>
    <body>
        <menu>
            <embed src='Audio/backgroundMusic.mp3' autoplay='true' loop='true' width='0' height='0'/>
            <input type='image' src='Images/start.jpg' width='275' height='150' onclick='INIT_GAME();'/>
        </menu>
    </body>
</html>

The script is producing an interesting black box effect, which is evident throughout the fade process. The reason for this is because the <input> tag is loading the scripts immediately from my JavaScript, which triggers the game I am making. I am trying to fade out the entire background and the button, and go straight to the game. It appears that the screen size changes as well, as scroll bars appear when the game is loaded. I don't want this effect either. My questions are:

  • How do I fade out the background image in my CSS body style?
  • How do I call the INIT_GAME() function AFTER the fadeOut has been completed?
  • Are the CSS styles I am using conflicting with the HTML elements I want to interact with due to the identical names?

You can view the effect here:
https://scrigbildefense-browntj.c9users.io/main.html

Any help is welcomed, thanks!

Answers 1

  • Here is how I would approach this.

    First, lets use event delegation in case this is dynamic content or we add any in the future, plus it allows us to drill down to the element you are really trying to influence which is the input.

     $(document).ready(function(){  
        //we start by targeting the click on the parent element of input    
         $('menu').on('click', 'input', function(){
            //then run init_game as a callback of fadeout
             $(this).fadeOut(1000, function(){
                   init_game();
             });
          });
      });
    
     function init_game(){
        console.log('the game is going!!');
      }
    
    //init_game can be removed from your html
    

Related Articles