Javascript Day3

Jisu Lee·2023년 2월 19일
0

오늘은 nomadcoders 강의를 통한 javascript 공부 세 번째 날입니다.

#4.0 (Input Values)

html (make input and a button)

<body>
<div id="login-form">
<input type="text" placeholder="What is your name?"/>
<button>Log In</button>
</div>
  <script src="app.js"></script>   
</body>

javascript (get the input and the button)

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");
const loginButton=loginForm.querySelector("button");
//the same thing is
const loginInput2=document.querySelector("#login-form input");
const loginButton2=document.querySelector("#login-form button");

display "clicked" when the login button is clicked

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");
const loginButton=loginForm.querySelector("button");


function onLoginBtnClick() {
    console.log("clicked")
}
loginButton.addEventListener("click",onLoginBtnClick);

the output

get the value when pressed the button

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");
const loginButton=loginForm.querySelector("button");


function onLoginBtnClick() {
    console.log(loginInput.value)
    }
loginButton.addEventListener("click",onLoginBtnClick);

the output

#4.1 (Form Submission)

using if statement for conditionals (alert when the value is empty or too long)

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");
const loginButton=loginForm.querySelector("button");

function onLoginBtnClick() {
    const username=loginInput.value;
    if (username===""){
        alert("Please write your name");
    }else if(username.length>15){
        alert("Your name is too long");
    }
    }
loginButton.addEventListener("click",onLoginBtnClick);

can set conditionals with html

<body>
<form id="login-form">
<input 
   required
   maxlength="15"
   type="text" 
   placeholder="What is your name?"/>
<button>Log In</button>

  <script src="app.js"></script>   
</body>

however everytime I press login button or press enter, the form will be submitted and the page will be refreshed -> we don't get to focus on clicking the button anymore and all we care is about submitting the form (value)

#4.2~4.3 (Events)

we don't need the button anymore as we are focusing on the submit action

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");


function onLoginSubmit() {
    const username=loginInput.value;
    console.log(username);
    }

loginForm.addEventListener("submit",onLoginSubmit);

stopping the page refresh from happening

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");


function onLoginSubmit(event) {
  	//stops the default behavior of the window such as refreshing the page
    event.preventDefault();
    console.log(loginInput.value);
    }

loginForm.addEventListener("submit",onLoginSubmit);

you are creating a function (onLoginSubmit) and giving that function one argument (event), when somebody submits the form, javascript will call the function with the event object, and the object has the function called preventDefault which will stop the default behaviors from happening

preventDefault 함수는 EventListener 함수의 '첫 번째 argument' 안에 있는 함수인데, 첫 argument는 지금 막 벌어진 event들에 대한 정보를 갖고 있다. JS는(기본적으로)argument를 담아서 함수를 호출하는데, 이 argument가 기본 정보들을 제공하고 있다. ex) 누가 submit주체인지, 몇 시에 submit을 했는지 등등 콘솔에 출력해보면 알 수 있음

another example with clicking link and moving on to a new website

<body>
<form id="login-form"> </form>
<a href="https://nomadcoders.com">Go to courses</a>
<script src="app.js"></script>   
</body>

javascript to set alert when the link is clicked (however does move on to the website when the alert is closed - default)

const link=document.querySelector("a");

function handleLinkClick(){
    alert("clicked");
}

link.addEventListener("click",handleLinkClick);

more about the object in the function

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

function onLoginSubmit(event) {
    event.preventDefault();
    console.log(loginInput.value);
    }

loginForm.addEventListener("submit",onLoginSubmit);

const link=document.querySelector("a");

function handleLinkClick(event){
    console.log(event);
    alert("clicked");
}

link.addEventListener("click",handleLinkClick);

//the first object(event) in the function(handleLinkClick) will the be information about the event(link being click) that just happened
//when console.log(event), there are many information that I can get, because it is a "click", this event is regarded as a pointerevent

the output

the browser will not lead us to the new website because we prevented the default action

onst link=document.querySelector("a");

function handleLinkClick(event){
    event.preventDefault();
}

link.addEventListener("click",handleLinkClick);

#4.4 (Getting Username)

step 1 (the user submits the username and the form disappears)
html script

<body>
   <form id="login-form">
   <input 
      required
      maxlength="15"
      type="text" 
      placeholder="What is your name?"/>
   <input type="submit" value="Log In"/>
   </form>
   <script src="app.js"></script>   
   </body>

css script (make a class called hidden)

.hidden{
    display:none;
}

javascript (css is triggered when the user inputs their username)

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

function onLoginSubmit(event) {
    event.preventDefault();
    const username=loginInput.value;
    loginForm.classList.add("hidden");
    console.log(username);
    }

loginForm.addEventListener("submit",onLoginSubmit);

step 2 (make the username appear)
html script (add ID called "greeting")

<body>
   <form id="login-form">
   <input 
      required
      maxlength="15"
      type="text" 
      placeholder="What is your name?"/>
   <input type="submit" value="Log In"/>
   </form>
   <h1 id="greeting" class="hidden"></h1>
   <script src="app.js"></script>   
   </body>

javascript

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");
//grabbing the id from the html script
const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save the username in a variable
    const username=loginInput.value;
 	//put some text inside the h1(greeting)
    greeting.innerText = "Hello " + username;
  	//h1 has the text but we need to remove the hidden class
    greeting.classList.remove(HIDDEN_CLASSNAME);
    }

loginForm.addEventListener("submit",onLoginSubmit);

displaying the username with different code ('는 숫자 1옆에 있는 물결표시와 함께 사용되는 자판을 이용할 것)

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save the username in a variable
    const username=loginInput.value;
    greeting.innerText = `Hello ${username} keep writing`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
    }

loginForm.addEventListener("submit",onLoginSubmit);

#4.5 (Saving Username)

there is an API (local storage) that has the program to remember values in the browser -> go to developer tools -> application and you can find the local storage

the first one is regarded as key and the second is regarded as value

localStorage.setItem("username","jisu")

the output

get the value

localStorage.getItem("username")

remove the value

localStorage.removeItem("username")

javascript to save the value

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save the username in a variable
    const username=loginInput.value;
  	//save the value in the local storage
    localStorage.setItem("username",username);
    //we take the empty h1 and fill it with username
    greeting.innerText = `Hello ${username} keep writing`;
    //remove the clasname named "hidden"
    greeting.classList.remove(HIDDEN_CLASSNAME);
    }

loginForm.addEventListener("submit",onLoginSubmit);

#4.6(Loading Username)

check if the user already exists in the local storage
when there is no username in the local storgae, the following code displays "null"

localStorage.getItem("username")

add a "hidden" class to the form so the browser displays nothing at first

<body>
   <form class="hidden" id="login-form">
   <input 
      required
      maxlength="15"
      type="text" 
      placeholder="What is your name?"/>
   <input type="submit" value="Log In"/>
   </form>
   <h1 id="greeting" class="hidden"></h1>
   <script src="app.js"></script>   
   </body>

if statement --> when the local storage is null, then the hidden class in the form is removed and the login form is displayed (onLoginSubmit function is executed), once it is saved then afterwards the browser keeps displaying "hello username"

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";
//when you are repeating strings, it is better to save them as constant variables 
const USERNAME_KEY = "username";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save the username in a variable
    const username=loginInput.value;
    localStorage.setItem(USERNAME_KEY,username);
    //we take the empty h1 and fill it with username
    greeting.innerText = `Hello ${username}`;
    //remove the clasname named "hidden"
    greeting.classList.remove(HIDDEN_CLASSNAME);
    }

const savedUsername=localStorage.getItem(USERNAME_KEY);
if (savedUsername===null){
    //show the form
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit",onLoginSubmit);
}else{
    //show the greeting comments
    greeting.innerText = `Hello ${savedUsername}`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

removing the same lines of code with a function called "paintGreetings"

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";
//when you are repeating strings, it is better to save them as constant variables 
const USERNAME_KEY = "username";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save the username in a variable
    const username=loginInput.value;
    localStorage.setItem(USERNAME_KEY,username);
  	//the username is coming from the loginInput.value
    paintGreetings(username);
    }

function paintGreetings(username){
    greeting.innerText = `Hello ${username}`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

const savedUsername=localStorage.getItem(USERNAME_KEY);
if (savedUsername===null){
    //show the form
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit",onLoginSubmit);
}else{
    //show the greeting comments
  	//the username is comming from the local storage
    paintGreetings(savedUsername);
}

paintGreetings() really don't have to receive anything, because we know there is a user in the local storage, however this way we search for the username two times with the code (localStorage.getItem(USERNAME_KEY);)

//search for the id
const loginForm=document.getElementById("login-form");
//inside of the id-form we search for the input and the button
const loginInput=loginForm.querySelector("input");

const greeting = document.querySelector("#greeting");

//uppercase variables are variables that are regarded to contain only strings
const HIDDEN_CLASSNAME = "hidden";
//when you are repeating strings, it is better to save them as constant variables 
const USERNAME_KEY = "username";

function onLoginSubmit(event) {
    //prevent the default event from happening
    event.preventDefault();
    //hide the form by adding the hidden classname
    loginForm.classList.add(HIDDEN_CLASSNAME);
    //save something on the local storage
    localStorage.setItem(USERNAME_KEY,username);
    //the moment we call the function, that username will already be saved on the local storage
    paintGreetings();
    }

function paintGreetings(){
  	//look for the username in the local storage
    const username= localStorage.getItem(USERNAME_KEY);
    greeting.innerText = `Hello ${username}`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

const savedUsername=localStorage.getItem(USERNAME_KEY);
if (savedUsername===null){
    //show the form
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit",onLoginSubmit);
}else{
    //show the greeting comments
    paintGreetings();
}

0개의 댓글