ruby メモアプリ

require 'date'

class Memo
  attr_accessor :title, :content, :category, :created_at

  def initialize(title, content, category)
    @title = title
    @content = content
    @category = category
    @created_at = DateTime.now
  end

  def to_s
    "#{@title}: #{@content} (Category: #{@category}) [Created at: #{@created_at}]"
  end
end

class MemoApp
  def initialize
    @memos = []
    load_memos
  end

  def run
    loop do
      show_menu
      choice = gets.chomp.to_i

      case choice
      when 1
        create_memo
      when 2
        display_memos
      when 3
        search_memos
      when 4
        break
      else
        puts "Invalid choice. Please try again."
      end
    end
  end

  private

  def show_menu
    puts "\nMemo App Menu"
    puts "1. Create Memo"
    puts "2. Display Memos"
    puts "3. Search Memos"
    puts "4. Exit"
    print "Enter your choice: "
  end

  def create_memo
    print "Enter memo title: "
    title = gets.chomp
    print "Enter memo content: "
    content = gets.chomp
    print "Enter memo category: "
    category = gets.chomp

    memo = Memo.new(title, content, category)
    @memos << memo
    save_memos
    puts "Memo created successfully!"
  end

  def display_memos
    if @memos.empty?
      puts "No memos found."
    else
      puts "\nMemos:"
      @memos.each_with_index do |memo, index|
        puts "#{index + 1}. #{memo}"
      end
    end
  end

  def search_memos
    print "Enter search term: "
    term = gets.chomp.downcase
    results = @memos.select { |memo| memo.title.downcase.include?(term) || memo.content.downcase.include?(term) || memo.category.downcase.include?(term) }
    if results.empty?
      puts "No memos found matching the search term."
    else
      puts "\nSearch Results:"
      results.each { |memo| puts memo }
    end
  end

  def load_memos
    if File.exist?("memos.txt")
      File.open("memos.txt", "r") do |file|
        file.each_line do |line|
          title, content, category, created_at = line.chomp.split(": ")
          @memos << Memo.new(title, content, category)
        end
      end
    end
  end

  def save_memos
    File.open("memos.txt", "w") do |file|
      @memos.each do |memo|
        file.puts "#{memo.title}: #{memo.content}: #{memo.category}: #{memo.created_at}"
      end
    end
  end
end

# メモアプリの実行
memo_app = MemoApp.new
memo_app.run

JQuery Todoリスト

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo リスト</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        input[type="text"] {
            width: 70%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            background-color: #4caf50;
            border: none;
            color: #fff;
            cursor: pointer;
            border-radius: 5px;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        ul {
            list-style-type: none;
            padding: 0;
        }
        li {
            padding: 10px;
            border-bottom: 1px solid #ccc;
            transition: background-color 0.3s;
            cursor: pointer;
        }
        li:hover {
            background-color: #f9f9f9;
        }
        .completed {
            text-decoration: line-through;
            color: #888;
        }
        .remove {
            float: right;
            color: #f44336;
            font-weight: bold;
        }
        .remove:hover {
            color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Todo リスト</h1>
        <input type="text" id="todoInput" placeholder="Todoを入力してください" autofocus>
        <button id="addButton">追加</button>
        <ul id="todoList">
        </ul>
        <button id="clearCompleted">完了済みを削除</button>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            // Todo追加処理
            $("#addButton").click(function(){
                addTodo();
            });

            // EnterキーでTodo追加
            $("#todoInput").keypress(function(event){
                if(event.which === 13) { // Enterキーのキーコードは13
                    addTodo();
                }
            });

            // Todo完了処理
            $(document).on("click", "li", function(){
                $(this).toggleClass("completed");
            });

            // Todo削除処理
            $(document).on("click", ".remove", function(event){
                event.stopPropagation(); // 親要素へのイベント伝播を停止
                $(this).parent().remove();
            });

            // 完了済みTodoを一括削除
            $("#clearCompleted").click(function(){
                $(".completed").remove();
            });

            // Todo追加関数
            function addTodo() {
                var todoItem = $("#todoInput").val().trim();
                if(todoItem !== "") {
                    $("#todoList").append("<li>" + todoItem + "<span class='remove'>[x]</span></li>");
                    $("#todoInput").val(""); // 入力フィールドをクリア
                    $("#todoInput").focus(); // フォーカスを入力フィールドに戻す
                }
            }
        });
    </script>
</body>
</html>

main.js

'use strict';

$(document).ready(() => {
    const $input = $('input');
    const $list = $('ul');
    const $clearCompleted = $('#clearCompleted');
    const todos = JSON.parse(localStorage.getItem('todos')) || [];

    // ローカルストレージからTodoアイテムを取得し、表示する
    todos.forEach(todo => {
        addTodoToList(todo.text, todo.completed);
    });

    $input.focus();

    $('#addButton').click(() => {
        const todoText = $input.val().trim();
        if (todoText !== '' && !isDuplicate(todoText)) {
            addTodoToList(todoText, false);
            saveTodos();
            $input.val('').focus();
        }
    });

    // EnterキーでTodo追加
    $input.keypress((event) => {
        if (event.which === 13) { // Enterキーのキーコードは13
            $('#addButton').click();
        }
    });

    // Todoアイテムの完了/未完了の切り替え
    $list.on('click', 'li', (e) => {
        const $target = $(e.target);
        if (!$target.hasClass('remove')) {
            const $todoItem = $target.closest('li');
            $todoItem.toggleClass('completed');
            updateCompletedCount();
            saveTodos();
        }
    });

    // 完了済みTodoアイテムの削除
    $clearCompleted.click(() => {
        $list.find('.completed').remove();
        updateCompletedCount();
        saveTodos();
    });

    // Todoアイテムをリストに追加する関数
    function addTodoToList(text, completed) {
        const $todoItem = $('<li>').text(text);
        if (completed) {
            $todoItem.addClass('completed');
        }
        $todoItem.append('<span class="remove">[x]</span>').appendTo($list);
        updateCompletedCount();
    }

    // Todoアイテムをローカルストレージに保存する関数
    function saveTodos() {
        const todos = [];
        $list.find('li').each((index, todo) => {
            todos.push({
                text: $(todo).text(),
                completed: $(todo).hasClass('completed')
            });
        });
        localStorage.setItem('todos', JSON.stringify(todos));
    }

    // 重複するTodoアイテムをチェックする関数
    function isDuplicate(text) {
        return $list.find('li').filter((index, todo) => $(todo).text() === text).length > 0;
    }

    // 完了済みアイテムの数を更新する関数
    function updateCompletedCount() {
        const completedCount = $list.find('.completed').length;
        $clearCompleted.text(`完了済みアイテムを削除 (${completedCount})`);
        if (completedCount === 0) {
            $clearCompleted.hide();
        } else {
            $clearCompleted.show();
        }
    }
});

JQuery WEBサービス

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Web Page</title>
    <style>
        .highlight {
            color: blue;
            font-weight: bold;
        }
        .listItem {
            cursor: pointer;
        }
        #inputField::placeholder {
            color: #999; /* ヒントテキストの色を設定 */
        }
    </style>
</head>
<body>

<h1>Interactive Web Page</h1>

<p>Type something in the input box below and click 'Add' to add it to the list:</p>

<input type="text" id="inputField" placeholder="Type here...">
<span id="charCount">0</span> characters
<button id="addButton">Add</button>

<ul id="listContainer">
    <!-- Items will be dynamically added here -->
</ul>

<script src="script.js"></script>
</body>
</html>

script.js

document.addEventListener("DOMContentLoaded", function() {
    var inputField = document.getElementById("inputField");
    var charCount = document.getElementById("charCount");
    var addButton = document.getElementById("addButton");
    var listContainer = document.getElementById("listContainer");

    inputField.addEventListener("input", function() {
        // 入力された文字数を更新
        charCount.textContent = inputField.value.length;
    });

    inputField.addEventListener("focus", function() {
        // 入力フォームがフォーカスされたときにヒントテキストを非表示にする
        inputField.placeholder = "";
    });

    inputField.addEventListener("blur", function() {
        // 入力フォームがフォーカスを失ったときにヒントテキストを再表示する
        inputField.placeholder = "Type here...";
    });

    addButton.addEventListener("click", function() {
        var userInput = inputField.value.trim();

        if (userInput !== "") {
            var listItem = document.createElement("li");
            var now = new Date(); // 現在の日時を取得
            listItem.textContent = userInput + " - " + now.toLocaleString(); // テキストと日時を結合して表示
            listItem.classList.add("listItem");

            // リストアイテムを追加する際にアニメーションを付ける
            listItem.style.opacity = "0"; // 最初は透明に設定
            listContainer.appendChild(listItem);
            listItem.style.transition = "opacity 0.5s"; // アニメーションの設定
            listItem.offsetHeight; // レンダリングをトリガーするためのダミー
            listItem.style.opacity = "1"; // 透明度を元に戻す

            inputField.value = "";
            charCount.textContent = "0"; // 文字数をリセット

            listItem.addEventListener("click", function() {
                listItem.classList.toggle("highlight"); // リストアイテムがクリックされたときに強調表示を切り替える
            });
        }
    });
});

jQuery style

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQueryの練習</title>
    <style>
        .red-text{
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <button>Go!</button>
    <p>こんにちは!</p>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="js/main.js"></script>
</body>
</html>

main.js

'use strict';

$(() => {
    $('button').click(() => {
        // $('p').text('おはよう!');
        // $('p').addClass('red-text');

          $('p')
          .text('おはよう!')
        .addClass('red-text'); 
    });
});

Javascript style属性

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <p style="color: red;">Hello</p>
  <button>OK</button>
  
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  document.querySelector('button').addEventListener('click', () => {
    //document.querySelector('p').style = 'font-size: 24px';
    document.querySelector('p').style.fontSize = '24px';
  });
}

Javascript お絵描きアプリ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Drawing App</title>
<style>
    canvas {
        border: 2px solid #000;
        cursor: crosshair;
    }
    #toolbar {
        margin-bottom: 10px;
    }
</style>
</head>
<body>
<div id="toolbar">
    <label for="colorPicker">Color:</label>
    <input type="color" id="colorPicker" value="#000">
    <label for="thickness">Thickness:</label>
    <input type="range" id="thickness" min="1" max="20" value="5">
    <button id="pencil">Pencil</button>
    <button id="line">Line</button>
    <button id="rectangle">Rectangle</button>
    <button id="circle">Circle</button>
    <button id="undo">Undo</button>
    <button id="redo">Redo</button>
    <button id="clear">Clear</button>
</div>
<canvas id="drawingCanvas" width="800" height="600"></canvas>

<script>
    const canvas = document.getElementById('drawingCanvas');
    const context = canvas.getContext('2d');
    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;
    let color = '#000';
    let thickness = 5;
    let isEraser = false;
    let lines = [];
    let currentLine = null;

    function startDrawing(e) {
        isDrawing = true;
        [lastX, lastY] = [e.offsetX, e.offsetY];
        currentLine = {
            color,
            thickness,
            points: [{ x: lastX, y: lastY }]
        };
    }

    function stopDrawing() {
        isDrawing = false;
        if (currentLine) {
            lines.push(currentLine);
            currentLine = null;
        }
    }

    function draw(e) {
        if (!isDrawing) return;

        const x = e.offsetX;
        const y = e.offsetY;

        context.beginPath();
        context.moveTo(lastX, lastY);
        context.lineTo(x, y);
        context.strokeStyle = isEraser ? '#fff' : color;
        context.lineWidth = isEraser ? thickness * 2 : thickness;
        context.lineCap = 'round';
        context.stroke();

        currentLine.points.push({ x, y });

        [lastX, lastY] = [x, y];
    }

    function changeColor(e) {
        color = e.target.value;
    }

    function changeThickness(e) {
        thickness = e.target.value;
    }

    function toggleEraser() {
        isEraser = !isEraser;
        document.getElementById('pencil').textContent = isEraser ? 'Pencil' : 'Eraser';
    }

    function drawLine() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawLinePreview);
        canvas.addEventListener('mouseup', drawLineFinish);
        canvas.addEventListener('mouseout', drawLineFinish);
    }

    function drawLinePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(lastX, lastY);
        context.lineTo(e.offsetX, e.offsetY);
        context.strokeStyle = color;
        context.lineWidth = thickness;
        context.lineCap = 'round';
        context.stroke();
    }

    function drawLineFinish(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        draw(e);
        canvas.removeEventListener('mousemove', drawLinePreview);
        canvas.removeEventListener('mouseup', drawLineFinish);
        canvas.removeEventListener('mouseout', drawLineFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function drawRectangle() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawRectanglePreview);
        canvas.addEventListener('mouseup', drawRectangleFinish);
        canvas.addEventListener('mouseout', drawRectangleFinish);
    }

    function drawRectanglePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        const width = e.offsetX - lastX;
        const height = e.offsetY - lastY;
        context.strokeRect(lastX, lastY, width, height);
    }

    function drawRectangleFinish(e) {
        if (!isDrawing) return;

        const width = e.offsetX - lastX;
        const height = e.offsetY - lastY;
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.strokeRect(lastX, lastY, width, height);
        stopDrawing();
        canvas.removeEventListener('mousemove', drawRectanglePreview);
        canvas.removeEventListener('mouseup', drawRectangleFinish);
        canvas.removeEventListener('mouseout', drawRectangleFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function drawCircle() {
        isEraser = false;
        document.getElementById('pencil').textContent = 'Pencil';
        canvas.removeEventListener('mousedown', startDrawing);
        canvas.removeEventListener('mousemove', draw);
        canvas.removeEventListener('mouseup', stopDrawing);
        canvas.removeEventListener('mouseout', stopDrawing);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', drawCirclePreview);
        canvas.addEventListener('mouseup', drawCircleFinish);
        canvas.addEventListener('mouseout', drawCircleFinish);
    }

    function drawCirclePreview(e) {
        if (!isDrawing) return;

        context.clearRect(0, 0, canvas.width, canvas.height);
        const radius = Math.sqrt(Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2));
        context.beginPath();
        context.arc(lastX, lastY, radius, 0, Math.PI * 2);
        context.stroke();
    }

    function drawCircleFinish(e) {
        if (!isDrawing) return;

        const radius = Math.sqrt(Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2));
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.arc(lastX, lastY, radius, 0, Math.PI * 2);
        context.stroke();
        stopDrawing();
        canvas.removeEventListener('mousemove', drawCirclePreview);
        canvas.removeEventListener('mouseup', drawCircleFinish);
        canvas.removeEventListener('mouseout', drawCircleFinish);
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
    }

    function undo() {
        lines.pop();
        redraw();
    }

    function redo() {
        // 未実装
    }

    function clearCanvas() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        lines = [];
    }

    function redraw() {
        clearCanvas();
        lines.forEach(line => {
            context.strokeStyle = line.color;
            context.lineWidth = line.thickness;
            context.beginPath();
            context.moveTo(line.points[0].x, line.points[0].y);
            line.points.forEach(point => context.lineTo(point.x, point.y));
            context.stroke();
        });
    }

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);

    document.getElementById('colorPicker').addEventListener('change', changeColor);
    document.getElementById('thickness').addEventListener('input', changeThickness);
    document.getElementById('pencil').addEventListener('click', toggleEraser);
    document.getElementById('line').addEventListener('click', drawLine);
    document.getElementById('rectangle').addEventListener('click', drawRectangle);
    document.getElementById('circle').addEventListener('click', drawCircle);
    document.getElementById('undo').addEventListener('click', undo);
    document.getElementById('redo').addEventListener('click', redo);
    document.getElementById('clear').addEventListener('click', clearCanvas);
</script>
</body>
</html>