Dynamic Position Dropdown with jQuery

Issue

all !
Here, I want to ask about jQuery….
How to make An element named ‘.eg-dropdown’….
Create this ‘.eg-dropdown’ element to fit right ‘.btn-dropdown’…..

Thanks, and Sorry for my less obvious English…..

Index.html

<div class="btn-dropdown">Publik</div>

<ul class="eg-dropdown">
 <li>Teman</li>
 <li>Pribadi</li>
</ul>

Index.css

.btn-dropdown {
  display: inline-block;
  width: 100px;
  height: 20px;
  position: absolute;
  top: 100px;
  left: 100px;
  background: green;
}

ul {
  margin: 0;
  padding: 0;
}

Index.js

// DROPDOWN
$(document).ready(function(){
 var position_btn = $('.btn-dropdown').position();
 $('.btn-dropdown').on('click', function(e){
  e.stopPropagation();
  console.log(position_btn);
 });

 $('.eg-dropdown').css({
  'position' : 'absolute',
  'top' : position_btn.top + $('.btn-dropdown').innerHeight(),
  'left' : position_btn.left
 });
});

SEE IN JSFIDDLE
https://jsfiddle.net/FIERMANDT/1kLvdys1/

Solution

Do it like below:

// DROPDOWN
$(document).ready(function(){
    var position_btn = $('.btn-dropdown').position();
    var widthBtn = $('.btn-dropdown').width();
    var widthEg = $('.btn-dropdown').height();
    $('.btn-dropdown').on('click', function(e){
        e.stopPropagation();
        console.log(widthEg);
    });

    $('.eg-dropdown').css({
        'position' : 'absolute',
        'top' : position_btn.top + $('.btn-dropdown').innerHeight(),
        'left' : position_btn.left + widthBtn - widthEg
    });
});

Working example:

$(document).ready(function(){
  var position_btn = $('.btn-dropdown').position();
  var widthBtn = $('.btn-dropdown').width();
  var widthEg = $('.btn-dropdown').height();
  $('.btn-dropdown').on('click', function(e){
    e.stopPropagation();
    console.log(widthEg);
  });

  $('.eg-dropdown').css({
    'position' : 'absolute',
    'top' : position_btn.top + $('.btn-dropdown').innerHeight(),
    'left' : position_btn.left + widthBtn - widthEg
  });
});
.btn-dropdown {
  display: inline-block;
  width: 100px;
  height: 20px;
  position: absolute;
  top: 100px;
  left: 100px;
  background: green;
}

ul {
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-dropdown">Publik</div>

<ul class="eg-dropdown">
 <li>Teman</li>
 <li>Pribadi</li>
</ul>

Answered By – Anant Kumar Singh

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.