jQueryUI Draggable: Bring stack element to front on click

If you are developing window-like elements on HTML using jQueryUI Draggable, you are probably using the stack option to ensure that the dragged element will always be on top. But the actual goal would be for that element to be on top onFocus, and that means whenever the user clicks on the element.

Exploring the jqueryUI source code for the Draggable widget we can extract the function that puts the element on top of the stack and bind it onClick for example.

Here is the function (Tweaked to work as a standalone function)

  1. function bringFront(elem, stack){
  2. // Brings a file to the stack front
  3. var min, group = $(stack);
  4.  
  5. if(group.length < 1) return;
  6. min = parseInt(group[0].style.zIndex, 10) || 0;
  7. $(group).each(function(i) {
  8. this.style.zIndex = min + i;
  9. });
  10.  
  11. if(elem == undefined) return;
  12. $(elem).css({'zIndex' : min + group.length});
  13. }

elem should be the clicked element and stack should be the same you put in jQueryUI draggable's options. If you wanted that to happen on click, you could use:

  1. $('.drag').bind('click',function(){ bringFront($(this), '.drag'); });

I hope this helps

About Alex

Hello! I'm Alejandro U. Alvarez, an engineering student at Universidad de Oviedo (Spain). I started programming during my Freshman year in Brookline High School (Boston, MA), and then got more and more interested in web development. I'm almost in love with JavaScript, although I keep an open mind with other languages

One thought on “jQueryUI Draggable: Bring stack element to front on click

Leave a Reply