Search code examples
jqueryjquery-effects

Appending text to the body background image with fadeToggle() effect


It is an important project for me and I have been trying to find a way how to prevent a text from being appended to the body over and over again. I have different slides which appear everytime when you hit the right arrow or up arrow keys. When you hit 'p' you pause slides and you will see a body background image. Using append() function I am adding a text to the image. Unfortunately, the text keeps being appended when you pause or play. So far I tried to use hide(), fadeOut(), one() even dequeue() to stop it but no success. How can I have the text to be appended to the body once ? fadeToggle() function works fine showing and hiding body background image only the text is causing an issue

  $(document).keyup(function(event) {
        var text = $("<p.text>PRESS 'P' TO GO BACK</p.text>");
        if(event.keyCode == 39 || event.keyCode == 40 ||   event.keyCode == 32) {
        next(); // right arrow and bottom arrow keys
        }
        else if(event.keyCode == 37 || event.keyCode == 38){
        back(); // left arrow and up arrow keys
        }
        else if(event.keyCode == 80){  // 'p' key to pause and play 
            $('.slides').fadeToggle();
            $('body').append(text).hide();
        }
    });

CSS:

   body {
    font-size: 2.5em;
    background: url("bodyBack.png");
}

It is not a complete code


Solution

  • try this .. and let me know Is that what you need or not

    var notappend = true;
         $(document).keyup(function(event) {
                var text = $("<p.text>PRESS 'P' TO GO BACK</p.text>");
                if(event.keyCode == 39 || event.keyCode == 40 ||   event.keyCode == 32) {
                next(); // right arrow and bottom arrow keys
                }
                else if(event.keyCode == 37 || event.keyCode == 38){
                back(); // left arrow and up arrow keys
                }
                else if(event.keyCode == 80){  // 'p' key to pause and play
                    $('.slides').fadeToggle(); 
                    if(notappend == true){
                        $('body').append(text);
                        notappend = false;
                    }else{
                        //notappend == true;
                    }
    
                }
            });
    

    try to work around notappend == true; and notappend == false; to get what you want