Omarobaisi
Omarobaisi

Reputation: 43

Using jquery in make a dropdown

I have this program which make a dropdown-content appear after clicking the ... button and disappear after clicking it again

So, I want the dropdown-content to disappear after clicking anywhere in the body

I tried a lot of ways but with every one of them the button stop working

The Code :-

JavaScript :

$(document).ready( function() {
  $(".commentdropdown .dropbtn").on("click", function(e){
    $(this).next('.dropdown-content').toggleClass("apear");
  });
});

CSS :

.commentdropdown{
    float: right;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
}

.apear{
    display: block;
}

HTML :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="commentdropdown pr-3">
    <button class="dropbtn btn p-0 m-0 bg-white">btn 1</button>
    <div class="dropdown-content">
        <a href="#">Edit 1</a>
        <a href="#">Delete 1</a>
    </div>

    <button class="dropbtn btn p-0 m-0 bg-white">btn 2</button>
    <div class="dropdown-content">
        <a href="#">Edit 2</a>
        <a href="#">Delete 2</a>
    </div>

    <button class="dropbtn btn p-0 m-0 bg-white">btn 3</button>
    <div class="dropdown-content">
        <a href="#">Edit 3</a>
        <a href="#">Delete 3</a>
    </div>
</div>

Upvotes: 0

Views: 52

Answers (1)

beatnik
beatnik

Reputation: 236

Heres a quick example. You dont really need the trigger to be a button as its not submitting anything. If you wrap each element in a parent container, its easier to target child elements.

$(function(){
    var dropdown = $('.dropdown');
    var toggle = dropdown.find('.dropdown__trigger');

    toggle.click(function(event){
        event.preventDefault();
        $(this).siblings().slideToggle();
    });
});
.dropdown__content{
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
<div class="dropdown__trigger p-0 m-0 bg-white">btn 1</div>
<div class="dropdown__content">
    <a href="#">Edit 1</a>
    <a href="#">Delete 1</a>
</div>
</div>
<div class="dropdown">
<div class="dropdown__trigger p-0 m-0 bg-white">btn 2</div>
<div class="dropdown__content">
    <a href="#">Edit 1</a>
    <a href="#">Delete 1</a>
</div>
</div>
<div class="dropdown">
<div class="dropdown__trigger p-0 m-0 bg-white">btn 3</div>
<div class="dropdown__content">
    <a href="#">Edit 1</a>
    <a href="#">Delete 1</a>
</div>
</div>

Upvotes: 1

Related Questions