Search code examples
javascriptjquerytizensamsung-smart-tvtizen-web-app

Detect Long Press on Enter/OK Key on a caph-list Item


I need to detect long press on Enter/OK key on an caph-list item. I am using the code below:

$("#channels-list-container").caphList({
    items: MyTVApp.groupChannels,
    template: "channels-list-item-template",
    direction: "vertical",

}).on("focused", function(event) {
    MyTVApp.focusedChannelIndex = Number(event.target.dataset.focusableName.split("channel")[1]);

}).on("selected", function(event) {
    var channelIndex = Number(event.target.dataset.focusableName.split("channel")[1]);
    var file = event.target.dataset.file;
    MyTVApp.displayPlayingScreen(file);
});

How can I detect long press on Enter/OK key when the focus is on an caph-list item?


Solution

  • As @basic already mentioned, you need some mechanism to detect the time passed between the first keydown and the keyup events.

    The code below should give you an example of how you could achieve this. Remember it is only an example and it might need to be adjusted to your specific needs, but it is designed to be a standalone and generic feature; it doesn't have any direct connection to your application logic.

    If you run the code sample below, focus the input field and press enter for at least one second, you should see a console log entry appear which detected the event.

    // Long-key-press event detection
    (function() {
      var duration = 1000,
          timer = null;
    
      $(document).on('keydown', function(event) {
        // Check if timer is already running.
        if(timer !== null) return;
    
        // Start new timer.
        timer = window.setInterval(function() {
          // Trigger longKeyPress event on the currently selected element when the timer finishes.
          $(event.target).trigger({
            type: 'longKeyPress',
            key: event.key,
            keyCode: event.keyCode,
            which: event.which
          });
        }, duration);
      });
      
      $(document).on('keyup', function(event) {
        if(timer === null) return;
        
        // Clear running timer.
        window.clearTimeout(timer);
        timer = null;
      });
    })();
    
    // Application logic
    (function() {
      // Bind to custom longKeyPress event.
      $('#channels-list-container').on('longKeyPress', function(event) {
        if(event.key === "Enter") {
          console.log('Long [Enter] key press detected on targeted element!');
        }
      });
    })();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="channels-list-container" type="text" />