1

I want a DIV to fade out, update its content, then fade back in as tidy as possible.

Current Way (http://jsfiddle.net/19czxx9r/2/)

$(".my_div").off().on('click', function(){
    $(".my_div").fadeOut(function(){
       $(".my_div").text("i was clicked");
        $(".my_div").fadeIn();    
    });
});

Ideal Way (http://jsfiddle.net/19czxx9r/1/)

$(".my_div").off().on('click', function(){
    $(".my_div").fadeOut();
    $(".my_div").text("i was clicked");
    $(".my_div").fadeIn();
});

I'd like to avoid the current way, which works, because I'll end up needing to nest tens of functions for my project.

Is there a way to efficiently queue the commands in the ideal way so they run after each one finishes?

Thanks

2
  • You can create and maintain your own queue(), but this is what jQuery is doing internally anyway. The latter cannot possibly work due to the async nature of the anmations. Can you give details about exactly why the first method would cause you to write 'tens of functions' Commented Oct 14, 2015 at 14:35
  • Hi Rory, example's tough but something along the lines of: > Fade DIV out > Update text > Slide in > Flash > Fade out > Update text again, to go through a fussy UI notification process Commented Oct 14, 2015 at 14:47

1 Answer 1

2

You could always write your own queue helpers:

$.fn.queueText = function(text){
    var jq = this;
    return jq.queue(function(){
        jq.text(text);
        jq.dequeue();
    });
};

var myDiv = $(".my_div");
myDiv.fadeOut().queueText('I was clicked').fadeIn();

$.fn.queueText = function (text) {
    var jq = this;
    return jq.queue(function () {
        jq.text(text);
        jq.dequeue();
    });
};

var myDiv = $(".my_div");

myDiv.off().on('click', function () {
    myDiv.fadeOut().queueText('I was clicked').fadeIn();
});
.my_div {
    font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_div">click me</div>

Sign up to request clarification or add additional context in comments.

4 Comments

Does this effectively mean that .fadeIn() is just $.fn.fadeIn, and it's a predefined prototype bundled in with jQuery, so we're making our own text changing prototype?
We are just making our queue helper and attaching it to the jQuery prototype. Also, yes, fadeIn is part of the jQuery prototype.
Gotcha, extrapolated this to make one for attribute too - works perfect. Thanks!
Just be extra careful with collisions of other jQuery prototype properties. (Notice how I used queueText instead of text as there's already a text property).

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.