Search code examples
javascripthtmllistdomspace-efficiency

Onclick with Ctrl hold duplicate one li element to another list


So basically what I need to do, is when I click on one UL list item, while holding Ctrl it needs to duplicate and that copy needs to go to another list, so far I've got to where only when I click on something it goes to another list with no Ctrl which is also mandatory for this homework. I'll upload script what I have so far:

var usersA = document.getElementById("users-a");
var usersB = document.getElementById("users-b");

var onclickA;
var onclickB = function() {
        usersA.appendChild(this);
        this.onclick = onclickA;
        return false;
    };
onclickA = function() {
        usersB.appendChild(this);
        this.onclick = onclickB;
        return false;
    };

for (var i=0; i < usersA.getElementsByTagName("li").length; i++)
    usersA.getElementsByTagName("li")[i].onclick = onclickA;
for (var i=0; i < usersB.getElementsByTagName("li").length; i++)      
    usersB.getElementsByTagName("li")[i].onclick = onclickB;

Any suggestions on how to do it with the least amount of code as possible? I mean do I need to create another event for that, I am lost, Thanks for any help!


Solution

  • To what I understand like you said. If the ctrl key is been pressed down and the li element is clicked. Basically there is not such way to detect if the ctrl key is been held down. But this trick below will return true on keydown and false on keyup. Therefore when the ctrl key is held down it is always true until it is been released

    var keys = {};
    onkeydown = onkeyup = function(e){
        e = e || event;
        keys[e.keyCode] = e.type == 'keydown';
        if(keys[17] == true){
            //the ctrl key is held down, so run your code here
        }
    }