input에 데이터를 입력을 받을때, 해당 코드 포맷에 맞추어 입력해줘야하는 요구가 있었다.

 

디테일한 요구조건

1. 숫자만 입력

2. {0000 0000} 포맷

3. max 8자

 

 

HTML

<label for="code"> 
  해당 코드를 입력해주세요.<br> 
  <span style="font-size:12px;">(EX : 1234 5678)</span><br>
</label> 

<input id="code" type="text">

 

JS

$('#code').on('input', function(){ 
  var thisVal = $(this).val().replace(/\s|\D/g, '');
  thisVal = thisVal.replace(/(\d{4})\B/g, '$1 ');
  thisVal = thisVal.substr(0,9); 

  $(this).val(thisVal); 
});	

 

CSS

#code{margin-top:10px; display:block;}

 

문자를 입력받게되면 빈값으로 치환했고 그 다음 한칸 스페이스와 포맷에 맞춰 삽입했다.

그리고 마지막으로 스페이스 포함 9자 이상일 경우 노출되지 않도록 9자까지만 subStr로 잘라서 해당 input에 넣어줬다.

 

예제

See the Pen accesscode input format example by leeyoonseo (@okayoon) on CodePen.

 

 

 

클릭 -> 스크롤 이동을 구현해보도록 하겠다.

scrollintoview()를 사용하면 간단하다.

 

 

HTML

<p>
  클릭하세요
  <button id="box1" type="button">box1</button>
  <button id="box2" type="button">box2</button>
  <button id="box3" type="button">box3</button>
  <button id="box4" type="button">box4</button>
  <button id="box5" type="button">box5</button>
  <button id="box6" type="button">box6</button>
  <button id="box7" type="button">box7</button>
</p>
<div class="box1">박스1입니다.</div>
<div class="box2">박스2입니다.</div>
<div class="box3">박스3입니다.</div>
<div class="box4">박스4입니다.</div>
<div class="box5">박스5입니다.</div>
<div class="box6">박스6입니다.</div>
<div class="box7">박스7입니다.</div>

클릭하여 이동할 수 있게 버튼을 만들어준다.

 

 

CSS

body,div{
  margin:0;
  padding:0;
}

div{
  display: flex;
  align-items: center;
  justify-content: center;
}

.box1{ background-color:red; }
.box2{ background-color:orange; }
.box3{ background-color:yellow; }
.box4{ background-color:green; }
.box5{ background-color:blue; }
.box6{ background-color:navy; }
.box7{ background-color:purple; }

 

 

JS

const btnArr = document.getElementsByTagName('button');

for(let i = 0; i < btnArr.length; i++){

  btnArr[i].addEventListener('click',function(e){
    e.preventDefault();
    document.querySelector('.box' + (i + 1)).scrollIntoView(true);
  });

}

 

버튼의 index를 이용해서 class를 검색하여 엘리먼트를 찾는다.

*index로 찾은 엘리먼트를 통해 scrollIntoView() 해주기 때문에 class나 id가 수정되면 스크립트 오류가난다.

 

예제

예제 버튼 클릭 시 티스토리 스크롤도 top되는 현상이 생겨버렸다.!! codePen가서 해보시길..

See the Pen scrollIntoView example by leeyoonseo (@okayoon) on CodePen.

 

크롬만 테스트했고, scrollintoview 메서드가 궁금하면 MDN을 살펴보자.

https://developer.mozilla.org/ko/docs/Web/API/Element/scrollIntoView

 

 


자동으로 연도 변경하여 삽입하기


사이트 하단에 회사 '창립 년도 ~ 현재 년도' 까지 적어두는 부분을 많이 봤을 것이다.

기업들이 보통 많이 작성해두는데, 수동으로 작성하는 곳은 없으리라 믿는다. 


캡쳐 : 삼성 홈페이지


자세히 보면 이렇게 ↓↓


HTML

<footer>
  2010~<span id="thisYear"></span>
</footer>
자동 값을 넣으려는 곳 id 값을 주었다.


JS

const _date = new Date();
const _year = _date.getFullYear();
const thisYear = document.getElementById('thisYear');

thisYear.innerText = _year;
id 값으로 변수를 만들어 그 안에 innerText해서 get한 값을 넣었다.


new Date(); 가 궁금하면 MDN을 참고하자!

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date



[예제]

See the Pen vVzNRx by leeyoonseo (@okayoon) on CodePen.


마우스 휠로 전체 페이지 영역 넘기기


지난번 마우스 휠로 input 넘버 값 up, down 작업을 했었다.

응용해서 작업 하나 더 했는데 올린다.


HTML

<div class="box1">박스1입니다.</div>
<div class="box2">박스2입니다.</div>
<div class="box3">박스3입니다.</div>
<div class="box4">박스4입니다.</div>
<div class="box5">박스5입니다.</div>
<div class="box6">박스6입니다.</div>
<div class="box7">박스7입니다.</div>

박스 7개 생성.

몇 개를 생성해도 상관없다.

하지만 구분을 위해 class로 css 추가했기 때문에 구분을 위한다면 똑같이 추가할 것. 


CSS

body,div{
  margin:0;
  padding:0;
}
div{
  display: flex;
  align-items: center;
  justify-content: center;
}
.box1{background-color:red;}
.box2{background-color:orange;}
.box3{background-color:yellow;}
.box4{background-color:green;}
.box5{background-color:blue;}
.box6{background-color:navy;}
.box7{background-color:purple;}


JS 수정 전

const _width = window.innerWidth;
const _height = window.innerHeight;
const boxArr = document.getElementsByTagName('div');

for(let i = 0; i < boxArr.length; i++){
  boxArr[i].style.width = _width + 'px';
  boxArr[i].style.height = _height + 'px';  
}

window.addEventListener('mousewheel', function(e){     
e.preventDefault();
   if(e.wheelDeltaY > 0){
     console.log('업');
     window.scrollTo(0,window.scrollY - _height);
   }else{
     console.log('다운');
     window.scrollTo(0,window.scrollY + _height);
   }
});
전체 페이지로 만들기 위해 window 크기 값을 가져와서 _width, _height 변수로 만들었다.   
반복문으로 각각에 _width, _height값을 주어 전체 페이지로 만들고

그 다음 마우스 휠 이벤트를 바인딩 해줬다.

마우스 휠 기본 이벤트를 막고 up, down 분기 코드로 현재 scrollTop위치에 박스 height 값을 더하거나 뺀 뒤 scrollTop 값이 되도록 했다.


+ mousewheel 이벤트는 예전에 브라우저 호환성 확인 안하고 작성한 스크립트를 가져다 썼기 때문에 호환이 안 될 수 있다. 


JS 수정내역!!

위의 js로 스크롤하게되면 스크롤하는 영역이 더해져서 (100px정도) 내가 원하는 페이지에 딱딱 안 멈추고 100px정도씩 어긋나는것이 확인된다.

따라서 window.scrollTo()에 들어가는 값에 스크롤 시 마다 내려가는 e.deltaY값을 빼줘야한다!

아래가 최종이다... 

근데 연속적으로 마우스 휠을하면 에러가 생기는데, jquery에서는 queue에 하나씩 들어가도록 stop()?메소드가 있는데, 아직 js는 모르겠다.

찾아서 다시 수정해야겠다..


JS 최종

const _width = window.innerWidth;
const _height = window.innerHeight;
const boxArr = document.getElementsByTagName('div');

for(let i = 0; i < boxArr.length; i++){
  boxArr[i].style.width = _width + 'px';
  boxArr[i].style.height = _height + 'px';  
}

window.addEventListener('mousewheel', function(e){     
e.preventDefault();
   if(e.wheelDeltaY > 0){
     console.log('업');
     window.scrollTo(0,window.scrollY - _height - e.deltaY);
   }else{
     console.log('다운');
     window.scrollTo(0,window.scrollY + _height - e.deltaY);
   }
});


[예제]

영역 안에서 마우스 휠을 업, 다운 해보도록!


See the Pen ePLmzp by leeyoonseo (@okayoon) on CodePen.



+ Recent posts