Rectangle 27 484

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  • Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  • 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  • It's the default! The fx queue is used by .animate() and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3));
$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});
var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

+1. I'm working on a jQuery-based user script that needs to connect to a PHP script as if it were another PHP script running on the client -- one HTTP request/other operation at a time, so this will definitely be helpful. Just a question: jQuery requires that queues be attached to objects, right? So which object should I use? $(window)?

@idealmachine - As seen in the Ajax Queue example, you can actually attach queue events to an empty object: $({})

This summary is incredibly useful. I just finished building a lazy loader for delaying the request for heavy content that's below the bottom of the screen until it's scrolled into view. Using jQuery's queue() made those Ajax requests very smooth (even if you jump straight to the bottom of the page). Thanks!

To add one thing for those just learning queues and promises etc - in the ajaxQueue example, the call to $.ajaxQueue() to which you put you ajax request you wish to queue inside the () will return a promise. The way you wait until the queue is empty is via promise.done(function(){ alert("done")});. Took me an hr to find this, so hope this helps someone else save their hr!

What are queues in jQuery? - Stack Overflow

jquery
Rectangle 27 9

By default, JQuery places animations in the effects queue so they will happen one after another. If you want an animation to happen immediately set the queue:false flag in your animate options map.

For example, in your case,

$(this).animate({
      opacity: "1"
    }, 600);

would become

$(this).animate(
{
    opacity: "1"
}, 
{
    duration:600,
    queue:false
});

You'd likely want to use the options map and set the queue for the border animation as well.

javascript - Simultaneous jQuery Animations - Stack Overflow

javascript jquery asynchronous jquery-animate
Rectangle 27 14

Your span9 div is jumping down due to the animation of the toggle effect jQuery adds, it animates both width and height so your content that is around the div that is being toggled gets pushed down as the animation goes. You can overcome this by speeding up the animation process down to something like 100 milliseconds or absolutely positioning the sidebar. And as for the margin issue that is due to the bootstrap.css itself, on line 222 we have the following:

.row-fluid > [class*="span"]:first-child {
  margin-left: 0;
}

The first-child pseudo-element attributes margin:0 to the first element, which in this case is the sidebar that is being toggled, so once the sidebar is hidden the second span tag (the content div) doesn't inherit this property and stays with the default margin applied to the span tag, e.g.

.row-fluid > [class*="span"] {
  float: left;
  margin-left: 2.127659574%;
}

You can overcome that margin issue with jQuery.

Here are a couple of demos i made:

Updated the fiddle with a fix for the issue a commenter found that i did not notice, now it works ok. Added a .no-sidebar class that is added upon toggling that removes the margin-left created by the bootstrap, so now it works with the responsive stylesheet just fine.

This is a great solution. However, I spotted an issue that you can see on your demos. Whenever you click on any element of the #content, your margin will change. Are you able to fix it?

@NelsonReis The margin changes because it is a fluid document, if you want a fixed document all you have to do is change the <div class="container-fluid"> to simply container and the <div class="row-fluid"> container to simply <div class="row">

@NelsonReis here is a patched version with no fluid marks, jsfiddle.net/dQ5b7/21

That's not what I meant. If you try to click on any element on the #content, like any text on your page, the margins will change. Seems like the event is being triggered on any element click, not when you click on the toggle element.

@NelsonReis updated the fiddle and now it works fine, added a class to toggle instead of toggling the css directly in jquery, this way the demo can support the media queries set by the responsive stylesheet. demo

jquery - Twitter Bootstrap fluid-container Sidebar Toggle - Stack Over...

jquery html css show-hide twitter-bootstrap
Rectangle 27 16

Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.

Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:

$("#element").click( function () {
    $('#element').transition({ opacity: 0 }, function () { $(this).remove(); });
});

The callback is not working - maybe it's due to a change in transit's api I don't know, but the fiddle example is not working. It triggers the hide method before the animation runs (tried in chrome)

Yea @ROFLwTIME you are totally right - it seems my chrome was just going crazy. Retested the fiddle today after a clean restart of chrome and it's working as expected. My bad ! Sorry 'bout this one.

javascript - Callback when CSS3 transition finishes - Stack Overflow

javascript jquery css css3
Rectangle 27 1

It seems newer versions of jQuery above 1.4.4 enable smooth background scrolling effects at a cost of breaking sprite animations that are in fact jerky relying on persistence of vision. I'd say the animate function was not intended for this, but it just worked (TM) back then.

google chrome - Why can't I animate backgroundPosition past jquery 1.4...

jquery google-chrome jquery-animate background-position
Rectangle 27 3

jQuery is a lightweight and feature-rich JavaScript Library that helps web developers
by simplifying the usage of client-side scripting for web applications using JavaScript.
It extensively simplifies using JavaScript on a website and its lightweight as well as fast.

So, using jQuery, we can:

easily manipulate the contents of a webpage
apply styles to make UI more attractive
easy DOM traversal
effects and animation
simple to make AJAX calls and
utilities and much more
AngularJS is a product by none other the Search Engine Giant Google and its an open source
MVC-based framework(considered to be the best and only next generation framework). AngularJS
is a great tool for building highly rich client-side web applications.

As being a framework, it dictates us to follow some rules and a structured approach. Its
not just a JavaScript library but a framework that is perfectly designed (framework tools
are designed to work together in a truly interconnected way).

In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:

Two-Way data binding
REST friendly
MVC-based Pattern
Deep Linking
Template
Form Validation
Dependency Injection
Localization
Full Testing Environment
Server Communication

javascript - How is AngularJS different from jQuery - Stack Overflow

javascript jquery angularjs
Rectangle 27 1

It's really just CSS and you could use jQuery if you wanted but most of your request can be handled by CSS. The only thing you may want to use jQuery for is animation effects.

<div class="nav">
   <ul>
      <li><a href="#">some link</a>
          <ul>
              <li>
                 <img arc="someimage.jpg" />
                 <p>some text you want to display</p>
              </ul>
          </ul>
      </li>
   </ul>
</div>
.nav ul ul { display: none; }
.nav img { float: left; }
.nav p { float: right; }
$(".nav li").on("click", function(){
   $( this ).children("ul").slideToggle(500);
});

You would probably want to constrain the images size as well by defining image width or height or both but this would be a good starting point. Also be sure to include the jQuery library.

@Jure Ravlic - Theres not error in the syntax if you look at the code you'll see that the ".nav li" has a onclick listener applied to it and that you target "this" the .nav li then its child "ul" which will display that child ul so I am not sure what you're talking about wrong syntax? Did you look at his example at all or read his remarks? The plugin you pointed him to does not do what he wants?

html - Jquery Dropdown menu with thumbnail Image - Stack Overflow

jquery html css drop-down-menu menu
Rectangle 27 1

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

html - Bootstrap image grid alignment - Stack Overflow

html css twitter-bootstrap image gridview
Rectangle 27 0

Depending on what you want to do animation-wise, jQuery might help you do it more easily, with reasonable performance.

html5 - Should I rely on CSS3 for animation, or use JavaScript for the...

javascript html5 animation css3 webkit
Rectangle 27 0

Here is the OOP solution,with Object literal way. also with method that you can change the Delay. and in the future you can add more methods like change case of string or change effects of animation with setters methods. you can append it to any element with any string. also it's not have dependencies like a jQuery. and this code you must put in the bottom of the DOM if you don't want dependency of jQuery or inside document ready func and with that you have dependency . Hope it's help you.

var animText =  {

        animStr: '',
        delay: 300,

        setDelay: function(delay) {
            this.delay = delay;
        },

        DoAnimation: function(string, selector) {

            this.animStr = string.split('');


            for (var i = 0; i <= string.length-1; i++) {

                setTimeout(function () {    
                    document.getElementById(selector).innerHTML += animText.animStr.shift();                 
                },this.delay * i);             
            };

            setTimeout( function() {                   
                document.getElementById(selector).innerHTML = '';                
                animText.DoAnimation(string, selector);                 

            }, this.delay * i + 1200) 

        }

    }


    animText.DoAnimation("Hello", "animStr");
    animText.setDelay(900);

javascript - How to automatically type text repeatedly - Stack Overflo...

javascript jquery loops text input
Rectangle 27 0

Here is the OOP solution,with Object literal way. also with method that you can change the Delay. and in the future you can add more methods like change case of string or change effects of animation with setters methods. you can append it to any element with any string. also it's not have dependencies like a jQuery. and this code you must put in the bottom of the DOM if you don't want dependency of jQuery or inside document ready func and with that you have dependency . Hope it's help you.

var animText =  {

        animStr: '',
        delay: 300,

        setDelay: function(delay) {
            this.delay = delay;
        },

        DoAnimation: function(string, selector) {

            this.animStr = string.split('');


            for (var i = 0; i <= string.length-1; i++) {

                setTimeout(function () {    
                    document.getElementById(selector).innerHTML += animText.animStr.shift();                 
                },this.delay * i);             
            };

            setTimeout( function() {                   
                document.getElementById(selector).innerHTML = '';                
                animText.DoAnimation(string, selector);                 

            }, this.delay * i + 1200) 

        }

    }


    animText.DoAnimation("Hello", "animStr");
    animText.setDelay(900);

javascript - How to automatically type text repeatedly - Stack Overflo...

javascript jquery loops text input
Rectangle 27 0

First off, the easy one - to stop the animation from queueing all the time, add in a call to .stop():

$('#navul').stop().animate({

As for the easing, do you definitely have the jQuery UI library loaded as well as jQuery itself? Only "swing" and "linear" easing is available natively, and you need to load in the UI to get the more exotic effects.

Yes, that's just the jQuery library, so you can only use "swing" and "linear" easing. You'll also need to pull in http://code.jquery.com/jquery-1.8.2.js in order to get access to "easeOut"

jquery - Easing wont work? - Stack Overflow

jquery jquery-animate easing
Rectangle 27 0

You could wrap your link and the div that does the animation in another div and then apply the hover to the parent div instead of the link. This way you will still validate. For example:

<div class="whatever">
    <a class="top-link-cart">Show login form</a>
    <div class="slidedown">form html goes here</div>
</div>

and the javascript would be:

jQuery(document).ready(function(){
    jQuery('.slidedown').hide();
    jQuery('.whatever').hover(function(){//to show
        jQuery('.slidedown').show('effect', duration in millisecs);
    }, function(){//to hide
        jQuery('.slidedown').hide('effect', duration in millisecs);
    });
});

this uses the jQueryUI for the animation effects, but you could use the .slideDown() and .slideUp() methods as well if all you need is the div to slide up or down

javascript - jquery dropdown div not quite working - Stack Overflow

javascript jquery html