2

Right, what I'd like to happen is when a button (or in this case, some text) is pressed, Jquery shows a div tag that contains an image, fades out the image after 2 seconds then displays some text.
This all works nicely, however I only want it to work once.
I decided to do this by using a variable and an if statement, so the variable changes from 0 to 1 and then the button cannot be clicked again due to the variable being changed.
Or at least, that's the badly worded version.

Anyhow, this is what I have so far, but for some reason the variable won't change from 0 to 1 after the button has been clicked, other than that, it works well.

The JS:

$(document).ready(function(){
    $("#text2").css("display","none");
    $("#ltt").css("display","none");
    var clicked = '0';
    if(clicked == 0) {
        $(".clicker").click(function() { 
            $("#ltt").fadeIn("slow");
            $('#ltt').delay(2000).fadeOut('slow');
            $("#text2").delay(3000).fadeIn(1000);
            $clicked = '1';
        });
    }
});

The HTML:

<div class="clicker">
    click to see text
</div>
<div id="ltt">
    <img src="Images/LoadingCircle.gif" width="24" height="24">
</div>
<div id="text2">
    SOME TEXT
</div>

4 Answers 4

1

Try to use .one() in this context,

$(".clicker").one('click', function() { 
    $("#ltt").fadeIn("slow");
    $('#ltt').delay(2000).fadeOut('slow');
    $("#text2").delay(3000).fadeIn(1000);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Aha, so that's how you do it! This code works perfectly, thank you!
1

You should use .one() instead:

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

$(".clicker").one('click',function() { 
  $("#ltt").fadeIn("slow");
  $('#ltt').delay(2000).fadeOut('slow');
  $("#text2").delay(3000).fadeIn(1000);
  $clicked = '1';
});

Comments

0

You declared the variable to

var clicked = '0'; 

but calling

$clicked = '1';

later on, so your variable will not be found.

Other than in PHP you don't need the Dollar $ to declare a variable, it's just a simple typo :)

Comments

0

well this should work :)

$(document).ready(function(){
    $("#text2").css("display","none");
    $("#ltt").css("display","none");
    window.clicked = false;
        $(".clicker").click(function() { 
            if(!window.clicked){
               $("#ltt").fadeIn("slow");
               $('#ltt').delay(2000).fadeOut('slow');
               $("#text2").delay(3000).fadeIn(1000);
               window.clicked = true;
            }
        });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.