user2498890
user2498890

Reputation: 1556

Alternate z-index between 2 divs on click?

I'm not great with JS so been using trial and error to try and figure out how to get 2 divs to swap z-index on the click of a trigger (button).

I currently have 2 drawers that technically are on top of each other and slide out from the right. On click of 'Buy' the #QuickShopDrawer should open and on click of 'Cart' or 'Add to Cart' the #CartDrawer should open.

Link to my test store.

My code so far is making the open with the #CartDrawer on top with a higher z-index.

JS:

Drawer.prototype.init = function () {
$(this.config.open).on('click', $.proxy(this.open, this));

$('.js-drawer-open-right-two').click(function(){
  $(this).data('clicked', true);
});

if($('.js-drawer-open-right-two').data('clicked')) {
  //clicked element, do-some-stuff
  $('#QuickShopDrawer').css('z-index', '999');
} else {
  //run function 2
  $('#CartDrawer').css('z-index', '999');
}

this.$drawer.find(this.config.close).on('click', $.proxy(this.close, this));
};

I've tried this which is more of what I want but it's only firing once?

$('.js-drawer-open-right-two').click(function() {
  var i = $(this).index();
  $('.drawer--right').hide();
  $('.drawer--right-two' + (i+1)).show();
});

Any help would be greatly appreciated!

Upvotes: 1

Views: 441

Answers (1)

Tushar
Tushar

Reputation: 87203

You need to swap the z-index of the elements on button click. Also, you can disable the button on click so that user cannot click it continiously.

Demo

$(document).ready(function() {
  $('#buy').on('click', function(e) {
    var myZindex = $('#QuickShopDrawer').css('z-index');
    $('#QuickShopDrawer').css('z-index', $('#CartDrawer').css('z-index'));
    $('#CartDrawer').css('z-index', myZindex);
    $(this).prop('disabled', true).siblings('button').prop('disabled', false);
  });

  $('#addToCart').on('click', function(e) {
    var myZindex = $('#CartDrawer').css('z-index');
    $('#CartDrawer').css('z-index', $('#QuickShopDrawer').css('z-index'));
    $('#QuickShopDrawer').css('z-index', myZindex);
    $(this).prop('disabled', true).siblings('button').prop('disabled', false);
  });

});
button {
  position: absolute;
  top: 150px;
  left: 0;
  clear: both;
}
#addToCart {
  margin-left: 50px;
}
.red {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: red;
  left: 20px;
  top: 20px;
  z-index: 1;
}
.green {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: green;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
  <div id="QuickShopDrawer" class="red">fdsafdsafdsa</div>
  <div id="CartDrawer" class="green">fdsafdsafdsa</div>
</div>
<button id="buy">Buy</button>
<button id="addToCart">Add To Cart</button>

Upvotes: 1

Related Questions