How to Handle HTML Events in Typescript

I have been getting lot of questions related to handling of events in Typescript. In this post, I will try to address these questions with focus on following:

  • How to handle click event for a button using Typescript?
  • How to handle keypress event inside a text box using Typescript?

To show, this I will take example of search panel that I implemented for my new blog framework.

<div class="document-search-panel">
    <div class="input-group u-shadow-v21 rounded g-mb-15">
        <input type="text" class="document-search-input" 
                 value="@Model.QueryPhrase" placeholder="Search ..." aria-label="Search">
        <div>
            <button class="search-button">
                <i class="fa fa-search"></i>
            </button>
        </div>
    </div>
</div>

For sake of brevity, I have removed all the style classes from HTML. I just want to focus elements and selectors that are participating in implementation. If you are interested in seeing the actual panel and its execution, you can visit World of Hobby Craft blog page.

Typescript Code

Following is actual code in action on my blog. One thing you will notice in the code is that there is no use of jQuery. It is not that I do not use jQuery in Typescript. For this particular implementation I did not need it. It will also show that for simple implementation, you don't need to include third party libraries if you don't want to.

import { portalConfig } from "../amgr.app";

export class SearchPanel {
    containerSelector: string;
    containerElement: HTMLElement;
    textInput: HTMLInputElement;

    initialize(containerSelect: string) {
        this.containerSelector = containerSelect;
        this.containerElement = document.querySelector(containerSelect) as HTMLElement;
        this.bindUiElements();
    }

    private bindUiElements() {
        const searchInput = this.containerElement.querySelector(".document-search-input");
        this.textInput = searchInput as HTMLInputElement;
        this.textInput.addEventListener("keypress", (e) => this.handleTextKeyPress(e));

        const button = this.containerElement.querySelector(".search-button");
        (button as HTMLElement).addEventListener("click", (e) => this.handleSearchButtonClick(e));
    }

    private handleTextKeyPress(e:KeyboardEvent) {
        if (e.key === "Enter") {
            const searchInput = e.target as HTMLInputElement;
            const searchTerm = $(searchInput).val() as string;
            this.doSearch(searchTerm);
        }
    }

    private handleSearchButtonClick(e: Event) {
        const searchTerm = this.textInput.value ;
        this.doSearch(searchTerm);
    }

    private doSearch(searchTerm: string) {
        if (searchTerm.length > 0) {
            document.location.href = `${portalConfig.baseUrl}/search?query=${searchTerm}`;
        }
    }
}

Search For Element

In initialize and bindUiElements, I have used querySelector method and passed it CSS class name as query selection criteria. This method returns the first element that matches the selection inside the container. If you call this method on document, then all document is searched. I have used both approaches here. First I looked for the container panel that encloses all search panel elements. And then I narrowed the search of text box and button inside this panel only. This approach ensures that if there is some other element on the page with same query selection criteria, it will be not included in the list.

Bind Elements To Events

After you have found the elements, you will use addEventListener method on each of the elements. You can see that I have factored handling of keypress in textbox and click on button in separate functions. An important that you will have to keep in mind about event handling. If your event handler needs access to event's parameters, you will need to implement the handling in lambda function and pass it the event parameters.

This is all you will need to handle different events on HTML elements when you use Typescript.

Search

Social

Weather

18.2 °C / 64.8 °F

weather conditions Clear

Monthly Posts

Blog Tags