Skip to main content
Participating Frequently
January 15, 2023
Question

Simulate a click and hold then a release using the keyboard

  • January 15, 2023
  • 2 replies
  • 500 views

I have an app where the user has to click and drag an item to the correct spot.  I want the user to be able to use the keyboard to do this. I want them to click A, b, c, d, to activate a particular spot then click 1 2 3 or 4 to tell them where to drop it. If not this kind of functionality any other suggestions are welcome. (i.e. move the across the stage using the arrows., etc.)

 

It's basically a drag and drop application.

    This topic has been closed for replies.

    2 replies

    JoãoCésar17023019
    Community Expert
    Community Expert
    January 16, 2023

    Hi.

     

    We need more details to suggest a better code, for now I would just like to suggest an approach for you to get started:

    // this sample assumes that you have pieces in the main timline named like pieceA, pieceB, pieceC, pieceD...
    // it also assumes that you have slots on stage named like slot0, slot1, slot2, slot3
    
    var piecesKeys = [ "a", "b", "c", "d" ];
    var slotKeys = [ "1", "2", "3", "4" ];
    var piecePrefix = "piece";
    var slotPrefix = "slot";
    var selectedPiece, targetSlot;
    
    function main()
    {
    	window.addEventListener("keydown", onKeyDown);
    }
    
    function onKeyDown(e)
    {
    	if (piecesKeys.indexOf(e.key) > -1)
    	{
    		selectPiece(0);
    		selectedPiece = root[piecePrefix + e.key.toUpperCase()];
    		selectPiece(1);
    	}
    	else if (slotKeys.indexOf(e.key) > -1)
    	{
    		if (selectedPiece && !selectedPiece.inPlace)
    		{
    			targetSlot = root[slotPrefix + e.key];
    			
    			if (!targetSlot.hasPiece)
    			{
    				selectedPiece.x = targetSlot.x;
    				selectedPiece.y = targetSlot.y;
    				selectedPiece.inPlace = true;
    				targetSlot.hasPiece = true;
    			}
    		}
    	}
    }
    
    function selectPiece(frame)
    {
    	if (selectedPiece && !selectedPiece.inPlace)
    		selectedPiece.gotoAndStop(frame);
    }
    
    window.root = this;
    main();

     

    I hope it helps.

     

    Regards,

    JC

    Community Expert
    January 17, 2023

    This is good code JoãoCésar I may use it myself. 

    kglad
    Community Expert
    Community Expert
    January 15, 2023

    you can use keyboard listeners

     

    window.addEventListener("keydown", downF.bind(this));
    window.addEventListener("keyup", upF.bind(this));