The CustomEvent of CustomEvent for JS works analogously to the constructor for Event except that the eventInitDict argument now allows for setting the detail attribute too.
event = new CustomEvent(type [, eventInitDict]) Allows setting the bubbles, cancelable, composed, and detail attributes.
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = event;
}
const type = "mouseover";
const event = new CustomEvent(type);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = event.bubbles;
}
const type = "mytype";
const eventInitDict =
{
bubbles: true
};
const event = new CustomEvent(type, eventInitDict);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = event.cancelable;
}
const type = "mytype";
const eventInitDict =
{
cancelable: true
};
const event = new CustomEvent(type, eventInitDict);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = event.composed;
}
const type = "mytype";
const eventInitDict =
{
composed: true
};
const event = new CustomEvent(type, eventInitDict);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = event.detail;
}
const type = "mytype";
const eventInitDict =
{
detail:
{
mydetail1: true,
mydetail2: "text"
}
};
const event = new CustomEvent(type, eventInitDict);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<output></output>
<script>
function myfunction(event)
{
document.querySelector("output").innerHTML = "bubbles: " + event.bubbles
+ "<br>cancelable: " + event.cancelable
+ "<br>composed: " + event.composed
+ "<br>detail: " + event.detail;
}
const type = "mytype";
const eventInitDict =
{
bubbles: true,
cancelable: true,
composed: true,
detail:
{
mydetail1: true,
mydetail2: "text"
}
};
const event = new CustomEvent(type, eventInitDict);
document.addEventListener(type, myfunction);
document.dispatchEvent(event);
</script>
</body>
</html>