반응형

== javascript 버전 ==

 

- textarea 의 줄바꿈 부분을 <br/>로 변경

 

var str = document.getElementById("textarea").value;

str = str.replace(/(?:\r\n|\r|\n)/g, '<br/>');

document.getElementById("textarea").value = str;

 

 

- <br/> 부분 줄바꿈 변경

 

var str = document.getElementById("textarea").value;

str = str.replaceAll("<br/>", "\r\n");

document.getElementById("textarea").value = str;

 

 

 

 

 

 

 

== jquery 버전 ==

 

- 줄바꿈 <br/>로 변경

 

var str = $('#textarea').val();

str = str.replace(/(?:\r\n|\r|\n)/g, '<br/>');

$('#textarea').val(str);

 

 

- <br/> 부분 줄바꿈 변경

 

var str = $('.#textarea').val();

str = str.split('<br/>').join("\r\n");

$('#textarea').val(str);

반응형
반응형

[javascript] 자바스크립트를 사용하여 현재 페이지를 새로고침, 갱신하지 않으면서 다른 주소로 변경하는 방법

 

History: pushState()

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

 

History: pushState() method - Web APIs | MDN

In an HTML document, the history.pushState() method adds an entry to the browser's session history stack.

developer.mozilla.org

history.pushstate(state, title, url)

state = 상태 값을 나타내는 것으로 브라우저에서 앞/ 뒤로 갈 때, 넘겨줄 데이터

title = 변경할 브라우저 제목 (변경을 원하지 않으면 null

url = 변경할 브라우저 URL

 

const state = { page_id: 1, user_id: 5 };
const url = "hello-world.html";

history.pushState(state, "", url);



const url = new URL(location);
url.searchParams.set("foo", "bar");
history.pushState({}, "", url);

검색 페이지나 페이지네이션(pagination)을 가진 페이지에서 많이 사용됩니다. 즉 검색 조건이나 페이지 전환이 비동기식 ajax로 이루어질때 이를 반영하기 위해 페이지 주소를 함께 변경하는 것입니다. 페이지 주소를 변경해두면 만약 페이지를 리로드, 갱신하더라도 바뀐 주소나 쿼리 스트링 정보를 그대로 가져올 수 있기 때문이죠.

pushstate()의 장점은 페이지 주소만 변경하는 것이 아니라 url 주소를 바꾸면서 동시에 데이터(state)를 전달하거나 타이틀 변경도 가능하다는 점입니다.

  • 데이터 state 값 전달 가능
  • 페이지 타이틀 변경

 

window.onpopstate = function(event) {
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
}

브라우저에서 뒤/앞으로 가는 버튼 클릭 시 onpopstate 이벤트가 발생하며 이때, 콜백함수에서 event.state는 pushState 함수의 인자 값이였던 state 객체가 넘어온 것이다.

 

onhashchange를 이용할 수도 있다. 

반응형
반응형

[jQuery]  URL에서 해시 값 가져오기

1. 모든 URL에 대한 해시 값 가져오기

순수한 JavaScript를 사용하면 주어진 값에서 해시 값을 얻을 수 있습니다. indexOf() 그리고 substring(), 아래에 설명된 대로:

var url = "https://mail.google.com/mail/u/0/#inbox";
var index = url.indexOf("#");
if (index !== -1)
{
    var hash = url.substring(index + 1);
    console.log(hash);
}
 

 
당신은 또한 사용할 수 있습니다 split() 방법 pop() 방법은 아래와 같습니다.

var url = "https://mail.google.com/mail/u/0/#inbox";
var parts = url.split('#');
if (parts.length > 1) {
    console.log(parts.pop());
}
 

2. 현재 URL의 해시 값 가져오기

또는 현재 창 URL에 대한 해시 값이 필요한 경우 다음을 사용할 수 있습니다. window.location.hash, 다음을 포함하는 문자열을 반환합니다. '#', URL의 조각 식별자가 뒤따릅니다. URL에 조각 식별자가 없으면 빈 문자열을 반환합니다. "".

// 'https://www.techiedelight.com/#input'에 대해 '#input'을 반환합니다.
var hash = window.location.hash;
 

 
jQuery를 사용하면 다음을 사용할 수 있습니다. .prop()  location 해시를 얻기 위한 객체:

// 'https://www.techiedelight.com/#input'에 대해 '#input' 반환
var hash = $(location).prop('hash');
 

 
URL의 조각 식별자만 추출하려면 '#', 당신은 사용할 수 있습니다 substr() 다음과 같은 방법:

// 'https://www.techiedelight.com/#input'에 대한 'input'을 반환합니다.

// JavaScript로
var hash = window.location.hash.substr(1);

// jQuery로
var hash = $(location).prop('hash').substr(1);
 

 
다음은 다음을 사용하는 또 다른 솔루션입니다. window.location.href.

// 'https://www.techiedelight.com/#input'에 대한 'input'을 반환합니다.
window.location.href.split('#').pop();​
반응형
반응형

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>

반응형

+ Recent posts