Background
The ComboBox control allows users to select an item from a dropdown list. To perform a custom action when a user clicks the control, attach a native JavaScript click event listener to its hostElement.
In JavaScript, you can register the listener immediately after creating the ComboBox.
Steps to Complete
- Add a container for the ComboBox.
- Import the ComboBox control and styles.
- Create the ComboBox.
- Add the click event listener.
Getting Started
Add a container for the ComboBox
<div id="theComboBox"></div>
- This element hosts the ComboBox control. The JavaScript code uses its ID to locate the container and initialize the control.
Import the ComboBox control and styles
import { ComboBox } from '@mescius/wijmo.input';
import '@mescius/wijmo.styles/wijmo.css';
- The imports provide the ComboBox control and its default appearance.
Create the ComboBox
const comboBox = new ComboBox('#theComboBox', {
itemsSource: ['US', 'Germany', 'UK', 'Japan']
});
- The constructor creates the ComboBox inside the specified container. The
itemsSourceproperty supplies the dropdown items.
Add the click event listener
function handleClick() {
console.log('ComboBox clicked');
}
comboBox.hostElement.addEventListener(
'click',
handleClick,
true
);
- The
hostElementproperty provides access to the DOM element that hosts the ComboBox. CallingaddEventListenerattaches the click handler to that element. -
The third argument,
true, registers the listener for the capture phase, allowing it to receive clicks as they travel toward elements inside the control. Replace the console message with the action your application needs to perform.
Combined code
import { ComboBox } from '@mescius/wijmo.input';
import '@mescius/wijmo.styles/wijmo.css';
const comboBox = new ComboBox('#theComboBox', {
itemsSource: ['US', 'Germany', 'UK', 'Japan']
});
function handleClick() {
console.log('ComboBox clicked');
}
comboBox.hostElement.addEventListener(
'click',
handleClick,
true
);
- This listener handles clicks within the ComboBox’s host element, including its input and dropdown button. It does not indicate that the selected item changed. Use
selectedIndexChangedwhen your action should respond to a selection change.
With this setup, the ComboBox responds to clicks through a native JavaScript event listener attached to its host element, allowing you to perform custom actions when users interact with the control.
Happy coding!
Andrew Peterson