javaScript

textarea에 포커스에 따라 placeholder 텍스트 지우고 호출하기

mooyou 2024. 1. 22. 22:11
728x90
300x250

 

스크립트를 이용해서 포커스가 될 경우 placeholder 기능 만들기 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        textarea {
            width: 100%;
            height: 150px;
            padding: 10px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }

        .placeholder {
            color: #999;
        }
    </style>
    <title>Textarea with Placeholder</title>
</head>
<body>

    <textarea id="myTextarea" class="placeholder" onfocus="clearPlaceholder()" onblur="restorePlaceholder()">Enter your text here...</textarea>

    <script>
        function clearPlaceholder() {
            var textarea = document.getElementById('myTextarea');
            if (textarea.value === 'Enter your text here...') {
                textarea.value = '';
                textarea.classList.remove('placeholder');
            }
        }

        function restorePlaceholder() {
            var textarea = document.getElementById('myTextarea');
            if (textarea.value === '') {
                textarea.value = 'Enter your text here...';
                textarea.classList.add('placeholder');
            }
        }
    </script>

</body>
</html>
728x90
반응형