JQuery - manipulating z-index & auto value instead of number

When you click the add new button, jQuery inserts the new dragrable DIVs into CONTAINER . When I click on part of these DIVs , I want to change the z-index value. But jQuery cannot get the z-index value as a number. It only shows 'auto' ... Is there a solution to show the true value of the z-index and increase it by 1 ?

JsFiddle example - http://jsfiddle.net/ynternet/84nVQ/10/

HTML

 <div id="add" style="background:yellow; width:100px;"> add new </div> <div id="container"> </div> 

JQuery

 function handler() { if ($(this).find("#menu").length) { return; } var currentIndex = $(this).css('z-index'); alert(currentIndex); var newIndex = currentIndex + 1; alert(newIndex); $(this).css('z-index', newIndex); } $("#add").on({ click: function(e) { var timestamp = Date.now(); var posx = Math.floor(Math.random() * 400); var posy = Math.floor(Math.random() * 400); $('#container').append(function() { return $('<div class="add_to_this" id="' + timestamp + '" style="left:' + posx + 'px; top:' + posy + 'px; ">Click me, drag a change z-index</div>').click(handler).draggable({ containment: "#container", scroll: false, cursor: 'lock' }); }); } }); 

CSS

 #container { width:500px; height:500px; background: palegoldenrod; position: relative; top:20px; left: 100px; padding: 0px; } .add_to_this { padding:5px; background:yellowgreen; position: absolute; display:inline-block; width:200px; height:50px; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; user-select: none; -o-user-select: none; } 
+4
source share
1 answer

Two problems in your code:

  • You don't have a real z-index to start with, because you haven't installed it, so you have 'auto'
  • you control the z-index string because you don't parse it

What you need to do:

  • add to css a z-index : z-index:100;
  • var currentIndex = parseInt($(this).css('z-index'), 10); z-index : var currentIndex = parseInt($(this).css('z-index'), 10);

DEMO (no warnings as they annoyed)

+5
source

Source: https://habr.com/ru/post/1438579/


All Articles