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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay