Enter Name
form-group">
Enter Occupation
text" name="name" id="name" autofocus />
form-group">
No Name Entered
No Occupation Entered
Here, we're adding the markup for the page.
The page has two sections. The first section is a form, which allows the user to do the
following:
© Upload an image via drag-and-drop or by manually selecting an image file
o Enter a name
© Enter an occupation
nps:ifsog [Link]-event-i-javaseripa-complete-qudel an7sans, 209M Custom events in JavaScript A complete guide - LogRocket Blog
The data gotten from the form will be displayed in the second section, which is the
profile card. The second section just contains some placeholder text and images. The
data received from the form will overwrite the content placeholder data.
Createa [Link] file and populate it with the following:
«i
box-sizing: border-box;
$
hag
text-align: centex;
$
main {
display: flex;
margin-top: 50px;
justify-content: space-evenly;
$
«form {
flex-basis: 500px;
border: solid 1px #cccecc;
padding: 10px 50px;
box-shadow: © © 3px #cecccc;
border-radius: 5px;
$
«form section {
border: dashed 2px #aaaaaa;
border-radius: 5px;
box-shadow: © © 3px #aaaaaa;
transition: all 0.2s;
margin-bottom: 30px;
padding: 50px;
font-size: 1.1zem;
$
-form section:hover {
box-shadow: © © 8px #aaaaaa;
border-color: #888888;
ntpsifsog [Link]-event-i-javaseript-a-complete-qudel
sn7sans, 209M Custom events in JavaScript: A complate guide - LogRocket Blog
$
.form section label {
text-decoration: underline #000000;
cursor: pointer;
$
.form-group {
margin-bottom: 25px;
$
.form-group label {
display: block;
margin-bottom: 1px;
$
.form-group input {
width: 100%;
padding: 1px;
border-radius: 5px;
border: solid 1px #cceccec;
box-shadow: @ © 2px #ccccce;
$
#file-input £
display: none;
$
-profile-card {
flex-basis: 300px;
border: solid 2px #cccecc;
border-radius: 5px;
box-shadow: @ © 5px #cccccc;
padding: 40px 35px;
align-self: center;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
$
~img-container {
margin-bottom: 5@px;
$
nipsifsog [Link]-events-i-javaseript-a-complete-qudel
son7+1128, 909M Custom evens in JavaScript A complete gude -LogRocket Blog
«img-container img {
border-radius: 50%;
width: 200px;
height: 200px;
$
-profile-card .name {
margin-bottom: 1px;
font-size: 1.5zem;
$
-profile-card occupation {
font-size: 1.2rem;
Lastly, create an index. js file so you can add functionality to the application.
JavaScript drag-and-drop
The first functionality we'll add to the application is the ability to upload images. For
this, we'll support drag-and-drop as well as manual upload.
Add the following to the JavaScript file:
const section = [Link](". form section");
[Link]("dragover", handleDragOver) ;
[Link]("dragenter", handleDragEnter) ;
[Link]("“drop", handleDrop) ;
[**
* @param {DragEvent} event
*/
function handleDragOver(event) {
// Only allow files to be dropped here.
if () {
return;
nipsifeog [Link]-event-i-javaseript-a-complete-qudel nar‘11276, 209 0 Custom evens in JavaScript A complete gude -LogRocket Blog
$
event. preventDefault();
// Specify Drop Effect.
[Link] = "copy";
[**
* @param {DragEvent} event
af
function handleDragenter(event) {
// Only allow files to be dropped here.
if ([Link]("Files")) {
return;
$
event. preventDefault () ;
[ee
* @param {DragEvent? event
*/
function handleDrop(event) {
event. preventDefault();
// Get the first item here since we only want one image
const file = [Link][0];
// Check that file is an image.
if () {
alert("Only image files are allowed.
return;
$
handleFileUpload (file) ;
Here, we're selecting the section from the DOM. This allows us listen on the
appropriate events that are required to allow drag-and-drop operations — namely,
dragover , dragenter , and drop .
nps:ifsog [Link]-event-i-javaseripa-complete-qudel van71112128, 9:09AM Custom events in JavaScript A complete guide - LogRocket Blog
For a deeper dive, check out our comprehensive tutorial on the HTML drag-and-
drop API.
Inthe handleDragOver function, we're ensuring that the item being dragged is a
fileand setting the drop effect to copy . handleDragEnter also performs a similar
function, ensuring that we're only handling the dragging of files.
The actual functionality happens when the file is dropped, and we handle that using
handleDrop . First, we prevent the browser's default action, which is to open a file
before delivering it.
‘We validate that the file is an image. If it’s not, we send an error message to let the
user know we only accept image files. If the validation passes, we proceed to process
the file in the handleFileUpload function, which we'll create next/
Update [Link] with the following:
/#*
* @param {File} file
*/
function handleFileUpload(file) £
const fileReader = new FileReader();
[Link]("load", (event) => {1
// Dispatch an event to the profile card containing the updated
dispatchCardEvent ({
image: [Link],
Dv:
vi
[Link] (file) ;
const profileCard = [Link](".profile-card");
const CARD_UPDATE_EVENT_NAME = "cardupdate
function dispatchCardEvent(data) {
[Link](
nipsifsog [Link]-events-i-javaseript-a-complete-qudel san7‘11276, 2090 Custom events in JavaScript Acomplate aide -LogRocket Blog
new CustomEvent (CARD_UPDATE_EVENT_NAME, {
detail: data,
3)
i
‘The handleFileUpload function takes in a file as a parameter and attempts to read
the file as a data URL using a file reader.
The FileReader constructor extends from EventTarget , which enables us to
listen in on events. The load event is fired after the image is loaded — in our case, as a
data URL.
You could also load images in other formats. MDN has a great documentation on the
FileReader API if you're looking to learn more about file readers.
Once the image has been loaded, we need to display it in the profile card. For this,
we'll dispatch a custom event, cardupdate , to the profile card.
dispatchCardEvent handles creating and dispatching the event to the profile card.
If you recall from the section above, custom events have a detail property, which
can be used to pass data around. In this case, we're passing an object containing the
image URL, which was gotten from the file reader.
Next, we need the profile card to listen for card updates and update the DOM
accordingly.
[Link]éventListener (CARD_UPDATE_EVENT_NAME, handleCardUpdat
[**
* @param {CustomEvent} event
*/
function handleCardUpdate(event) {
const { image } = [Link];
if (image) i
nipsifsog [Link]-events-i-javaseript-a-complete-qudel sanr1112128, [Link] Custom events in JavaSccipt A complete guide - LogRocket Blog
[Link]("img").src = image;
As shown above, you simply add the event listener as you normally would and call the
handleCardUpdate function when the event is triggered.
How to use object destructuring in JavaScript
handleCardUpdate receives the event as a parameter. Using object destructuring,
you can get the image property from [Link] . Next, set the src attribute
of the image in the profile card to be the image URL gotten from the event.
To allow users to upload images via the input field:
const fileInput = [Link]("#file-input");
[Link]("change", (event) => {
handleFileUpload (event. target. files[0]);
v:
‘When a user selects an image, the change event will be triggered on file input. We
can handle the upload of the first image since we only need one image for the profile
card.
Now we don’t need need to do anything new since we developed all the functionality
when adding support for drag-and-drop.
‘The next functionality to add is updating name and occupation:
const nameInput = [Link]("s#name") ;
const occupationInput = [Link]("#occupation") ;
hitpsfolog [Link]/custom-events-in-javascrpt-a-complete-guide/ ssn7sans, 209M Custom events in JavaScript A complete guide - LogRocket Blog
occupationInput .addEventListener("change", (event) => {
dispatchCardevent({
occupation: [Link],
b:
n;
[Link]("change", (event) => {
dispatchCardEvent ({
name: [Link],
Dd:
D:
For this, we're listening on the change event and dispatching the card update event,
but this time with different data. We need to update the handler to be able to handle
more than images.
azam {CustomEvent} event
function handleCardUpdate(event) {
const { image, name, occupation } = [Link];
if (image) £
[Link]("img").sre = image;
}
if (name) £
profilecard. quezyse:
3
if (occupation) {
ctor("[Link]").textContent = name;
profilecard. querySelector("[Link]").textContent = occupation;
Update the handleCardUpdate function to look like the above snippet. Here, again,
we're using object destructuring to get the image, name, and occupation from
[Link] . After getting the data, we display them on the profile card.
hitpsolog [Link]/custom-events-in-javascrpt-a-complete-guidel s6n71112128, 9:09AM Custom events in JavaScript A complete guide - LogRocket Blog
Conclusion
It’s sometimes easier to understand your code when you think of it in terms of events
— both custom and native DOM events — being dispatched. JavaScript custom.
events can enhance the user experience of your app when used properly. No surprise,
then, that it’s included in some of the top JavaScript frameworks, such as [Link] (in
‘Vue, you dispatch custom events using $emit ).
The code for the demo used in this tutorial is available on GitHub.
#vanilla javascript
nps:ifoog [Link]-events-i-javaseripta-complete-gudel amr