Help trapping CTRL + click in custom element

I am creating a multi-date-picker custom element that allows a user to pick a series of dates. The idea is if the user simply clicks a date, that starts the date selection over and all previously selected dates are cleared from the selection array. If the user holds CTRL and clicks a date, that date is added to the array of selected dates.

The problem I’m having is trying to figure out how to know if the CTRL key is being held down when the user clicks on a date. There is no input element involved with my custom element so it doesn’t appear that keydown.trigger is available to me.

I tried the following:

export class DatePickerCustomElement {
    constructor(){
        this.keyPressCallback = this.keyPress.bind(this);
        ...
    }

    keyPress(e){
        console.log(e);
    }

    attached(){
        window.addEventListener('keypress', this.keyPressCallback, false)
    }

    detached(){
        window.removeEventListener('keypress', this.keyPressCallback)
    }
}

However, this never seems to work. Any ideas?

1 Like

I think the keypress event is being deprecated, have you tried keydown instead?

I also use document instead of window, although not sure if that matters. Technically, you should use the injected DOM element instead of globals.

You can then check the target of the event to make sure the user is clicking on your custom element?

Lastly, I think you can just use something like

attached(){
    document.addEventListener('keydown', this.keyPress.bind(this), false);
}

instead of creating a field in the constructor.

1 Like

Well, I don’t know why I was making this so difficult. The more I thought about it, the more I realized that I can simply add a click.delegate to each “day” on the calendar and pass the event to my VM. The MouseEvent actually has a ctrlKey property that indicates if the CTRL key was held down.

selectDate(date: Date, e : MouseEvent){
    if(!e.ctrlKey)
        this.selectedDates = [];
    ...
}
<div repeat.for="day of days" click.delegate="selectDate(day,$event)">${day}</div>
1 Like