skip to Main Content
var input  = document.createElement("input");
input.type = "datetime-local";

input.onchange =
function()
{ 
 console.log("date set");
} 

input.showPicker();

The code above will show a Date/Time picker.
Upon selecting a date, the onchange even is fired, as expected.

However, if the user simply clicks outside the picker, to cancel,
what event – if any – gets fired?

onblur doesn’t seem to work.

So far the only very ugly solution I could find,
is to create a full window, top-layer invisible div,
and capture the "exit click" through that.

2

Answers


  1. Chosen as BEST ANSWER

    Answers were right that the picker could not be shown unless a user action triggered it: I was testing from the console only, and from the console apparently this constraint doesn't apply.

    The element also needs to be appended to the DOM.

    focus(), however, will not work if the element has any of these characteristics:

    • display:none
    • visibility:hidden
    • zIndex less than 0

    Finally I had to resort to setting the input's height and width to 0, but also opacity to 0, because a few pixels would still show.

    https://www.number137.com/lab/picker/

    <html>
        <body style = "display:flex; justify-content:center; align-items:center">
            <div id = "picker" style = "cursor:hand">Pick</div>
        </body>
    </html>
    
    <script>
    
    document.getElementById("picker").onclick =
    function()
    {
     var input = document.createElement("input");
     input.type             = "datetime-local";
     input.style.position   = "absolute";
     input.style.zIndex     = - 10;
     input.style.width      = "0px";
     input.style.height     = "0px";
     input.style.opacity    = 0;
     
     document.body.appendChild(input);
    
     input.onchange = 
     function(event)
     {
      console.log(input.value);
     } 
    
     input.onblur = 
     function(event)
     {
      console.log("nothing");
     }
     
     input.showPicker(); 
     input.focus();
    }
    
    </script>
    

  2. Set onblur listener, and immediately after you call showPicker, set it to be focused as well, so that the blur triggers (which is why it doesn’t work now, because there was no focus event, when picker gets shown programmatically).

    (Note: to trigger native datepicker programmatically, it requires a user action)

    Try this:

    var input  = document.createElement("input");
    input.type = "datetime-local";
    
    document.querySelector('#test').append(input);
    
    input.onchange =
    function()
    { 
     console.log("date set");
    } 
    
    input.onblur =
    function()
    { 
     console.log("closed onblur");
    } 
    
    input.showPicker();
    
    input.focus();
    <div id="test"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search