0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

bootstrap5 と jqueryでチャット画面を作る

Posted at

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Chat UI</title>
<!-- jQuery 3.5.1 -->
<script src="https://code.jquery.com/jquery-3.5.1.js"
	integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
	crossorigin="anonymous"></script>
<!-- bootstrap 5 -->
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
	crossorigin="anonymous">
    <style>
        .chat-box {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-box" id="chatBox"></div>
        <div class="input-group">
            <input type="text" class="form-control" id="messageInput" placeholder="メッセージを入力してください...">
            <button class="btn btn-primary" id="sendBtn">送信</button>
        </div>
    </div>
    <script src="chat.js"></script>
</body>
</html>

JavaSript

$(document).ready(function() {
    // 事前にチャット履歴をロードします(デモ用にハードコード)
    var chatHistory = ['Hello, User!', 'How can I help you today?', 'You: Hi there!'];
    chatHistory.forEach(function(message) {
        $('#chatBox').append($('<p>').text(message));
    });

    // 新しいメッセージが入力されたときにチャットボックスに追加します
    $('#sendBtn').click(function() {
        var message = $('#messageInput').val();
        if (message) {
            $('#chatBox').append($('<p>').text('You: ' + message));
            $('#messageInput').val('');
            scrollToBottom();
        }
    });

    // チャットボックスのスクロールを最下部に保つ関数
    function scrollToBottom() {
        $('#chatBox').scrollTop($('#chatBox')[0].scrollHeight);
    }

    // チャット履歴がロードされた後にスクロールを最下部にスクロールします
    scrollToBottom();
});

結果

こんな感じになります。

image.png

謝辞

本投稿の作成に際して ChatGPT 様には大変なお世話になりました。
ありがとうございます。

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?