반응형
반응형

With the rapidly changing technologies, developers are being provided with incredible new tools and APIs. But it has been seen that out of the 100+ APIs, only 5% of them are actively used by developers.

Let’s take a look at some of the useful Web APIs that can help you skyrocket your website to the moon! 🌕🚀

1. Screen Capture API

The Screen Capture API, as the name suggests, allows you to capture the contents of a screen, making the process of building a screen recorder a piece of cake.

You need a video element to display the captured screen. The start button will start the screen capture.

<video id="preview" autoplay>
  Your browser doesn't support HTML5.
</video>
<button id="start" class="btn">Start</button>
const previewElem = document.getElementById("preview");
const startBtn = document.getElementById("start");

async function startRecording() {
  previewElem.srcObject =
    await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: true,
    });
}
startBtn.addEventListener("click", startRecording);

2. Web Share API

The Web Share API allows you to share text, links, and even files from a web page to other apps installed on the device.

async function shareHandler() {
  navigator.share({
    title: "Tapajyoti Bose | Portfolio",
    text: "Check out my website",
    url: "https://tapajyoti-bose.vercel.app/",
  });
}

NOTE: To use the Web Share API, you need an interaction from the user. For example, a button click or a touch event.

3. Intersection Observer API

The Intersection Observer API allows you to detect when an element enters or leaves the viewport. This is exceptionally useful for implementing infinite scroll.

 

NOTE: The demo uses React because of my personal preference, but you can use any framework or vanilla JavaScript.

4. Clipboard API

The Clipboard API allows you to read and write data to the clipboard. This is useful for implementing the copy to clipboard functionality.

async function copyHandler() {
  const text = "https://tapajyoti-bose.vercel.app/";
  navigator.clipboard.writeText(text);
}

5. Screen Wake Lock API

Ever wondered how YouTube prevents the screen from being switched off while playing the video? Well, that’s because of the Screen Wake Lock API.

let wakeLock = null;

async function lockHandler() {
  wakeLock = await navigator.wakeLock.request("screen");
}

async function releaseHandler() {
  await wakeLock.release();
  wakeLock = null;
}j

NOTE: You can only use the Screen Wake Lock API if the page is already visible on the screen. Otherwise, it would throw an error.

6. Screen Orientation API

The Screen Orientation API allows you to check the current orientation of the screen and even lock it to a specific orientation.

async function lockHandler() {
  await screen.orientation.lock("portrait");
}

function releaseHandler() {
  screen.orientation.unlock();
}

function getOrientation() {
  return screen.orientation.type;
}

7. Fullscreen API

The Fullscreen API allows you to display an element or the entire page in full screen.

async function enterFullscreen() {
  await document.documentElement.requestFullscreen();
}

async function exitFullscreen() {
  await document.exitFullscreen();
}

NOTE: To use the Fullscreen API too, you need an interaction from the user.

 

 

https://tapajyoti-bose.medium.com/7-javascript-web-apis-to-build-futuristic-websites-you-didnt-know-12b737ccf594

반응형
반응형

입력창 글자수 제한

<div class="form-group col-12" >
  <div class="textLengthWrap">
    <p class="textCount">0자</p>
    <p class="textTotal">/200자</p>
  </div>
  <textarea style="height:300px; resize: none;" maxlength="200" placeholder="텍스트를 입력하세요.">
  </textarea>	
</div>

$('#textBox').keyup(function (e) {
	let content = $(this).val();
    
    // 글자수 세기
    if (content.length == 0 || content == '') {
    	$('.textCount').text('0자');
    } else {
    	$('.textCount').text(content.length + '자');
    }
    
    // 글자수 제한
    if (content.length > 200) {
    	// 200자 부터는 타이핑 되지 않도록
        $(this).val($(this).val().substring(0, 200));
        // 200자 넘으면 알림창 뜨도록
        alert('글자수는 200자까지 입력 가능합니다.');
    };
});
반응형
반응형

1. keyup

키보드에서 손을 땠을 때 실행

2. keydown

키보드를 눌렀을 때 실행

키보드를 누르고 있을 때 한번만 실행됨

3. keypress

키보드를 눌렀을 때 실행

키보드를 누르고 있을 때 계속 실행됨

 

* Ctrl, Alt, Shift 키 등은 keydown에서는 작동하지만 keypress 에서 작동하지 않음

 

* keyCode ASCII code 값

keydown, keyup에서는 a = 65, A = 65로 동일하게 보여짐

keypress에서는 a = 97, A = 65로 다른 값이 보여짐

 -> Caps Lock 여부 체크, 대소문자 구분을 통한 로직 작성 가능

 

* FireFox 에서의 버그

event.keyCode 가 파이어폭스에서 동작안할 수 있음 따라서 keyCode 사용 시 아래와 같이 사용하면 됨

 

var keyCode = event.keyCode ? event.keyCode : event.which;

 







keydown, keypress 는 이전 누른 값을 가지고 있음

keyup 은 한글 처리 가능 및 현재 누른 값을 가지고 있음

반응형
반응형

1. $(document).ready()

- 외부 리소스. 이미지와는 상관 없이 브라우저가 DOM (document object model) 트리를 생성한 직후 실행
- window.load() 보다 더 빠르게 실행되고 중복 사용하여 실행해도 선언한 순서대로 실행됨
  

2. $(window).load()

- DOM의 standard 이벤트
- html의 로딩이 끝난 후에 시작
- 화면에 필요한 모든 요소(css, js, image, iframe etc..)들이 웹 브라우저 메모리에 모두 올려진 다음에 실행됨
- 화면이 모두 그려진 다음의 메세징이나 이미지가 관련 요소가 모두 올려진 다음의 애니메이션에 적합함
- 전체 페이지의 모든 외부 리소스와 이미지가 브러우저에 불려운 이후 작동하게 되어 이미지가 안뜨너가 딜레이가 생길 때에는 그만큼의 시간을 기다려야 함
- 외부 링크나 파일 인크루트시 그 안에 window.load 스크립트가 있으면 둘 중 하나만 적용됨
- body onload 이벤트와 같이 body에서 onload 이벤트를 쓰게 되면 모든 window.load() 가 실행되지 않는 현상이 발생함
 

* window > document
- document는 window의 자식 객체
  (window의 자식 객체 : document, self, navigator, screen, forms, history, location etc..)
- document : html의 요소들이나 속성들에 접근할 시 사용하는 객체

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(window).load(function() {
    console.log("console> window.onloade() 첫번째");
});
 
$(window).load(function() {
    console.log("console> window.onload() 두번째");
});
 
$(document).ready(function() {
    console.log("console> document.ready() 첫번째");
});
 
$(document).ready(function() {
    console.log("console> document.ready() 두번째");
});
</script>
 
</head>
<body>
 
</body>
</html>
반응형
반응형

화면 리사이즈시 사이즈 확인 및 미디어쿼리 확인

 

Typical Media Query Breakpoints

https://jsfiddle.net/mill01/1jedsc76/8/

 

media queries - JSFiddle - Code Playground

 

jsfiddle.net

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>

.example {
  padding: 20px;
  color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
  .example {background: red;}
}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
  .example {background: green;}
}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
  .example {background: blue;}
} 

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
  .example {background: orange;}
} 

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
  .example {background: pink;}
}
</style>
<script>
$( window ).resize(function() {
   //창크기 변화 감지
   var windowWidth = $( window ).width();
   $("#width_size").val(windowWidth);
});
</script>
</head>
<body>

<h2>Typical Media Query Breakpoints</h2>
<input type="text" id="width_size" >
<p class="example">Resize the browser window to see how the background color of this paragraph changes on different screen sizes.</p>

</body>
</html>

반응형
반응형

KeyboardEvent keyCode

<!DOCTYPE html>
<html>
<body>
<h1>Keyboard Events</h1>
<h2>The keyCode Property</h2>

<p>Press a keyboard key in the input field and display the value:</p>

<input type="text" size="40"   onkeypress="myFunction(event)">

<p id="demo"></p>
<p>The keyCode property is deprecated, use the key property instead.</p>

<script>
function myFunction(event) {
  let value= event.which;
  document.getElementById("demo").innerHTML = value;
}  
</script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
	$("#inp").keypress(function(e){
		//검색어 입력 후 엔터키 입력하면 조회버튼 클릭
		if(e.keyCode && e.keyCode == 13){
			$("#btn").trigger("click");
			return false;
		}
		//엔터키 막기
		if(e.keyCode && e.keyCode == 13){
			  e.preventDefault();	
		}
	});
	$("#btn").click(function(){
		alert("이벤트 감지");
	});
});
</script>
<input type="text" class="form-control input-sm" id="inp" name="inp">
<button type="button" class="btn btn-primary btn-sm" id="btn" name="btn">조회</button>
</body>
</html>

 

 

반응형

+ Recent posts