Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to increase the z-index of matched element by 1, without iteration?

I have to increase the z-index by 1, of all span with class .page. There can be more than 100 matched elements (NOT more than 150 in any case). Right now I am iterating through each one of them and changing the z-index via following code.

  $('#mydiv span.page').each(function() {
    var zi = parseInt($(this).css('z-index')) + 1;
    $(this).css('z-index', zi);
  });

Is there a better way to deal with it for better performance. I am using jQuery.

like image 383
ʞɹᴉʞ ǝʌɐp Avatar asked Sep 09 '13 06:09

ʞɹᴉʞ ǝʌɐp


People also ask

How do you use Z-index without position?

z-index has no effect for position:static (the default).

How does a higher z-index value affect a positioned element?

The z-index property determines the stack level of an HTML element. The “stack level” refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher value means the element will be closer to the top of the stacking order.

How do I fix a Z-index problem?

To sum up, most issues with z-index can be solved by following these two guidelines: Check that the elements have their position set and z-index numbers in the correct order. Make sure that you don't have parent elements limiting the z-index level of their children.


2 Answers

Some tricky way is,

Create new style

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { z-index: value; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('yourElementId').className = 'cssClass';
like image 73
Jaykishan Avatar answered Oct 14 '22 01:10

Jaykishan


The best way would be to rewrite your logic not to depend on a uniform incremental z-index in the element styling. If you are only ever running this logic once, perhaps you can set up some general CSS rules that just involve toggling a class to achieve the layout you want. Assuming that is not an option, there isn't much you can do to make it more performant.

You may be able to detach the '#mydiv' element temporarily to reduce page repainting but it is hard to give more help without more info, and that can confuse other things.

var div = $('#mydiv');
var prev = div.prev();
div.detach();

// You can clean up your jQuery like this:
div.find('span.page').css('z-index', function(index, zIndex) {
    return parseInt(zIndex, 10) + 1;
});

div.insertAfter(prev);
like image 23
loganfsmyth Avatar answered Oct 14 '22 00:10

loganfsmyth