I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Looping thru elements, changing z index, Javascript

I have a set of elements with that are draggable with jquery. All draggable elements belong to the "element" class.

Each time an element is moved, I want to loop through all elements and change the z-index to 5, and then change the element being dragged z-index to 10, so that the dragged element will always be on top.

This is what I currently have but it is not working.

mousedown(function(){
        var myObj = document.getElementsByClassName('element');
        for(var i =0, il = myObj.length; i<il; i++){
            myObj[i].style.zIndex='5';
        }
        $(this).style.zIndex='10';
 })

How can I force $(this) to be displayed on top of all other elements in the element class?

Upvotes: 1

Views: 895

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

Without seeing the rest of the css and element structure not much is possible, but whatever you have done can be written as

$('.element').not(this).css('zIndex', 5);
$(this).css('zIndex', 10);
//or this.style.zIndex='10';

The style property belongs to the dom element, $(this) refers to the jQuery wrapper for the dom element refered by this. So either you can set the style property directly using this.style or use the .css() to do this.

Also you can use the class selector to select and change all the elements zIndex instead of writing a loop yourself

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22405

$(this) refers to a jQuery object, not a document object. Use this.style.zIndex="10"; instead.

Since you did not invoke any jQuery, there is no $(this) to reference!

Upvotes: 3

Related Questions