DEV Community

ktr92
ktr92

Posted on

[html css jquery] Reusable script for dropdown elements

Here is reusable jquery script for dropdown elements. You can keep every dropdown open at the same time or hide all other dropdowns when you open one.

You can add a new dropdown element declaratively via html. You need to add the attribute data-toggleclick="some-id" for a button and data-toggleblock="some-id" for a dropdown block.

codepen demo: https://codepen.io/ktr92/pen/LYgyqZE

Solution example

HTML

<div>
  <div class="wrapper">
    <button data-toggleclick="block1">Open block 1</button>
    <div data-toggleblock="block1">
      Block 1 
    </div>
  </div>
  <div class="wrapper">
    <button data-toggleclick="block2" >Open block 2</button>
    <div data-toggleblock="block2">
      Block 2
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

[data-toggleblock] {
  display: none;
}

[data-toggleblock].active {
  display: block;
}

.container {
  width: 320px;
}

.wrapper {
  height: 100px;
  position: relative;
  width: 320px;
}
[data-toggleblock] {
  padding: 10px;
  border: 1px solid #000;
  margin-bottom: 30px;
  position: absolute;
  top: 50px;
  width: 100%;
  z-index: 1;
}
[data-toggleclick] {
  background: #ccc;
  padding: 10px 10px;
  border: none;
  display: block;
  width: 100%;
  font-size: 20px;
}
Enter fullscreen mode Exit fullscreen mode

JS (jquery)

// show element by click on button 
$('[data-toggleclick]').each(function() {
  $(this).on('click', function(e) {
        $(this).toggleClass('active')
        e.preventDefault()
        let dropdown = $(this).data('toggleclick')
        // if you want to hide all other dropdowns
        // $('[data-toggleblock].active').not($(`[data-toggle=${dropdown}]`)).removeClass('active')
        // $('[data-toggleclick].active').not($(`[data-toggleclick=${dropdown}]`)).removeClass('active')
        $(`[data-toggleblock=${dropdown}]`).toggleClass('active')
  })
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)