ToggleEvent: source property
The source
read-only property of the ToggleEvent
interface is an Element
object instance representing the HTML popover control element that initiated the toggle.
A <button>
or <input type="button">
element can be specified as a popover control by specifying the id
of the popover element in its commandfor
or popovertarget
attribute.
Value
An Element
object instance, or null
if the popover does not have a control element (for example, if the popover is being controlled using a JavaScript method such as HTMLElement.togglePopover()
).
Examples
Basic source
usage
This demo shows how to use the source
property to perform a different action depending on which control button was used to close a popover.
HTML
Our markup contains a <button>
, a <p>
, and a <div>
element. The <div>
is designated as an auto
popover, and the button is designated as a control for showing the popover using the commandfor
and command
attributes.
The popover contains a heading asking the user if they would like a cookie, and two buttons allowing them to select an answer of "yes" or "no". Each one of these buttons is designated as a control for hiding the popover.
<button commandfor="popover" command="show-popover">
Select cookie preference
</button>
<p id="output"></p>
<div id="popover" popover="auto">
<h3>Would you like a cookie?</h3>
<button id="yes" commandfor="popover" command="hide-popover">Yes</button>
<button id="no" commandfor="popover" command="hide-popover">No</button>
</div>
JavaScript
In our script, we start off by grabbing references to the "yes" and "no" buttons, the popover, and the output <p>
.
const yesBtn = document.getElementById("yes");
const noBtn = document.getElementById("no");
const popover = document.getElementById("popover");
const output = document.getElementById("output");
We then add a toggle
event listener to the popover. When fired, it checks if the "yes" or the "no" button was used to toggle (hide) the popover; an appropriate message is printed to the output <p>
in each case.
popover.addEventListener("toggle", (event) => {
if (event.source === yesBtn) {
output.textContent = "Cookie set!";
} else if (event.source === noBtn) {
output.textContent = "No cookie set.";
}
});
Result
Specifications
No specification found
No specification data found for api.ToggleEvent.source
.
Check for problems with this page or contribute a missing spec_url
to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.