Quatban Taco Quatban Taco - 7 months ago 11
Javascript Question

How to make elements interact with each other and position with jquery

$(document).ready(function() {
//ENTRANCE

$("#first").css("top", -1000);
setTimeout(function() {
$("#first").animate({
top: 10
}, 400);
}, 200);

$("#second").css("top", -1000);
setTimeout(function() {
$("#second").animate({
top: 10 + 45 + 15
}, 400);
}, 400);

$("#third").css("top", -1000);
setTimeout(function() {
$("#third").animate({
top: 10 + 45 + 45 + 30
}, 400);
}, 600);

$("#four").css("top", -1000);
setTimeout(function() {
$("#four").animate({
top: 10 + 45 + 45 + 45 + 45
}, 400);
}, 800);

//EXIT
$('#first').on('click', function() {
$('#first').toggle();
$('#second').animate({top: 5}, 400);
});

$('#second').on('click', function() {
$('#second').toggle();
$('#third').animate({top: 5}, 400);
});

$('#third').on('click', function() {
$('#third').toggle();
$('#four').animate({top: 5}, 400);
});

$('#four').on('click', function() {
window.location.reload();
});
});


`
I have been trying for a while to make elements interact with each other using jquery, Here is a
Fiddle of my code.
I have although been having a few hiccups.


  1. In a real world environment, elements may not be called in ascending or logical order.

  2. Items do not animate properly when closed, there are gaps and in some cases, some items do not move depending on which is clicked.

  3. There may be more than 4 items.



Here is my question: How can i make the elements animate and cover properly regardless of which item is clicked and what order the items are sorted.

Answer

Please see this fiddle

var elements = $('.menu');// Here you can write any selector to get list of elements
elements.on('click', function() {
  $(this).toggle();
  var nextEleemnts = $(this).nextAll('.menu'); // Same selector will follow here
  for (var i = 0; i < nextEleemnts.length; i++) {
    var topPos = $(nextEleemnts[i]).position().top - 60; //little bit of counting
    $(nextEleemnts[i]).animate({
      top: topPos
    }, 400);
  }
});

There is also a good solution and straight forward solution provided to you by a guy in comment, For this you need to do a bit of change in CSS as well, so if you don't want to do it, then you can take my approach as well.

Here I am talking an alternate approach, here what I am doing whenever you click on any element I am finding it's next siblings and position them up by 60 pixels.