GreatCoder
GreatCoder

Reputation: 99

Make a div able to run onclick function when it is clicked

I am creating an options menu for a notes-app. I want to make the menu show when you click the three-dots(these are stored in a div). When I put an onclick with a function on the element, it does not run the function. I want to know how to make this div clickable, if this is the problem. Adding the click event listener from javascript works only for the existing note I have, but I add new notes from javascript later, and this does not work with the javascript notes. This is the code:

function showOptions() {
  alert('hi');
  $('#delete').closest('.options-menu').fadeToggle(200);
}
<div class="option-holder">
  <input type="text" name="note-title" id="note-title" placeholder="Your note title">
  <div class="note-options">
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
  </div>
  <div class="options-menu" onclick="showOptions()">
      <h3 id="delete">Delete</h3>
  </div>
</div>

Please tell me how to get the click function working. Thank you!

Upvotes: 1

Views: 1041

Answers (1)

Ivan86
Ivan86

Reputation: 5708

You can do this in jQuery using the .on() method since the items are being added dynamically to the DOM.

$(document).on('click', 'div.options-menu', function() {
    alert('hi');
    $('#delete').closest('.options-menu').fadeToggle(200);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="option-holder">
  <input type="text" name="note-title" id="note-title" placeholder="Your note title">
  <div class="note-options">
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
  </div>
  <div class="options-menu">
      <h3 id="delete">Delete</h3>
  </div>
</div>

Upvotes: 1

Related Questions