0

Basically the point of the code is that its a dropdown. The dropdown is initially displayed to none and when it is clicked a active dropdown class is added on to it. The problem is that once its added its not working when I try to use jquery to hear for a click.

html

<button onclick="dropdown_btn()" type="button" style="background: none; border:none; font-size: 25px; 
        font-weight: bold; position: relative; top: 29%; cursor: pointer; outline: none" id="user-page" class = 'user-dashboard-dropdown'>
        <img width="50" src="{% static 'imgs/user-icon.png' %}">
</button>

<div class="dropdown-for-user" style="display:none">
     <ul style="list-style-type: none;">
     <li><a href="{% url 'profile' %}">Profile</a></li>
     <li><a href="{% url 'account' %}">Account</a></li>
     <li><a href="{% url 'saved-items' %}">Saved Items</a></li>
     <li><a href="{% url 'listed-items' %}">Listed Items</a></li>
     <li style="border-bottom: none;"><a href="{% url 'logout' %}">Logout</a></li></ul></div>

jquery/javascript

   function dropdown_btn(){
        $('.user-dashboard-dropdown').addClass('active-dropdown');
        $('.dropdown-for-user').css('display', '');
    
    }
    
    $('.user-dashboard-dropdown.active-dropdown').click(function(){
        alert('ran');
        $(this).removeClass('active-dropdown');
        $('.dropdown-for-user').css('display', 'none');
    });
  • `$('.dropdown-for-user').css('display', '');` set the value. empty not going to work – Empty Brain Dec 31 '20 at 21:52
  • the thing is that the whole $('.user-dashboard-dropdown.active-dropdown') is not being run at all. The display, ' ', works already. –  Dec 31 '20 at 21:53
  • While the element isn't being *created* dynamically, the linked duplicate still applies. The element is being *modified* dynamically. So the event handler wasn't attached when you first tried to attach it. Using `.on()` on a parent element and filtering based on class would solve that. – David Dec 31 '20 at 21:53

1 Answers1

0

You can use event delegation.

$(document).on('click', '.user-dashboard-dropdown.active-dropdown', function(){
        alert('ran');
        $(this).removeClass('active-dropdown');
        $('.dropdown-for-user').css('display', 'none');
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80