Today, I leanred about the Event Object in Javascript.
In Javascript, the browser will construct an event object that contains information about the event when an event is triggered.
We already know there are:
- e.type: the type of the event (click, focus, blur)
- e.target: the element that triggered event
- e.pageX: the horizontal coordinate of the mouse pointer upon click
- e.pageY: the vertical coordinate of the mouse pointer upon click
- e.key: the value of the key in case of a keyboard event
Here is an another example of event object example 2:
This code helps us to figure it out which keyboard we pressed.
In this time, I would like to move the mustache if I click the mouse button on the pumpkin image.
p.addEventListener("click", mustacheMove); --> If I click on the pumpkin image, then it triggers the mustacheMove() function.
x, y have the value of horizontal coordinate and vertical coordinate in it.
The mustache image position should be "absolute" to move to correct location.
If we click the mouse, mouse cursor is not on the middle of image. So, that's why we put (x-100/2) and (y-70/2) to send the image for correct location. 100 and 70 is the size of the mustache image!๐ง๐ปโ๏ธ
Now, I would like to talk about the preventDefault() method.
- The preventDefault() method cancels the default action of an event.
- Clicking on a "Submit" button: do not submit the form!
- Clicking on a link: do not go to that link!
Before doing exercise, we should know about the from submit event in Javascript.
- When the form is submitted this event is triggered.
- We can do some prevalidation of the form in JavaScript before sending the data on the server.
Now, we are gonna do an exercise to do preventDefault() and form submit event.
I make the "Guess a Number" game. Every page has a random number between 1 and 100. If we submit smaller number, then we show the message "too small, try again." If we submit bigger number, then we show the message "too large, try again."
This is the algorithms. node get value from id. In html, if we push the submit button, the function is triggered.
const g is the value we put on html input. If we put nothing and submit, then we should show the message "Please enter a number."
isNaN() checks the input is number or not.
Before I put the e.preventDefault(), the message disapper as soon as I submit the value. We should remain the message which we have tried, so we should put the preventDefault().
'Web Programming ๐ > Front-End ๐ฆธ๐ปโโ๏ธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Javascript DOM "radio checked" (0) | 2023.04.19 |
---|---|
Javascript Event Exercise to Move Picture (0) | 2023.04.15 |
Javascript Events, Apr/08/2023 (0) | 2023.04.09 |
Javascript Event Handling, Apr/5/2023 (0) | 2023.04.06 |
Position of Elements, DOM family in Javascript, Apr/5/2023 (0) | 2023.04.06 |