Search code examples
javascriptjquerydomclickdropdown

Run javascript function on click dropdown menu


How to run a javascript function in HTML page only when a dropdown menu is selected, before any option is selected in it. I run Query when dropdown menu is clicked on, with the following:

$("#_id").click(function () {

Then when I select something in the same dropdown menu, script runs again. When it's clicked on dropdown menu and when an option is selected. How to prevent from running again when I select something?


Solution

  • What is the usecase? We prefer dropdowns to only do stuff when we change them

    To answer:

    Mousedown triggers before click

    Click and hold the mouse to see the mousedown, release to see the click

    $("#_id").on("click",function() { console.log("clicked")});
    $("#_id").on("mousedown",function() { console.log("mousedown")});
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <select id="_id">
    <option value="">Please select</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    </select>