How to prevent text selection in html


Its necessary to prevent text selection when the text is ui feature, to make the webpage more professional.

We can prevent the text from selecting by using this in css

user-select: none;

You cannot select this text

You can select this text

example code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <p style="user-select: none;">You cannot select this text</p>
    <p>You can select this text</p>
</body>
</html>

How to create tooltip in html

Is essential to add tooltip to make web page more professional and understandable

The simplest way can we add tooltip is use html inline element <span>

We will add the tool in div and tooltip text(tool description) in the span

Toll description will be always hide ( display none in css) until the user hover the tool text , then it will show the tool

A simple example

Tooltip Example
Tooltip Example. This line has tooltip!
This is the tooltip Text!

The example code


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tooltip Example</title>
<style>
  .tooltip-main {
    background-color: blue;
    color: white;
    position: relative;
  }
  
  .tooltip-text {
    position: absolute;
    display: none;
    background-color: wheat;
    padding: 5px;
    border-radius: 3px;
  }
  
  .tooltip-main:hover + .tooltip-text {
    display: inline;
  }
</style>
</head>
<body>
<div>
  <div class="tooltip-main">Tooltip Example. This line has tooltip!</div>
  <span class="tooltip-text">This is the tooltip Text!</span>
</div>
</body>
</html>



Create your first chat application with Flask and Socketio

We will use socketio for real-time messaging

First install our dependency for this application


pip install flask
pip install flask-socketio


How it will work.

Every user will get an unique key.

If the the other user submit the other users key that will send the message. its like sending message to unique username

Generate Unique Key for every user


import string
import random
def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))
generated_key=generate_key()
print(generated_key)


Its a 4 digit key for testing purpose. In real application must use long key with other randomness to make sure two key will not be same. Instead of key we can use unique user name. Thas another topic . For simplicity we will use this 4 digit key. Uptate it later on your necessary.

Our application structure….

stept by step Explanation

when the user load the page on borwer they will go to this page

@app.route('/')
def index():
    return render_template('index.html')

After loading the page they will connect with the socketio they will get an uniuqe key

and this key will send to the user by emiting the key to the client

also save the key in the python dictionary with the socketio sid to handle users connection activity later

When the user connected with socketio

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

When the user disconnected from socketio

If the user diconnected we will remove the user from the python dictionary.( its like active user management)

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

When the user will send menssage to specific user.( the logic handles on serverside socketio)

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)


The Complete Server Side code


from flask import Flask, render_template,request
from flask_socketio import SocketIO, emit
import random
import string

app = Flask(__name__)
socketio = SocketIO(app)
active_connections = {} 


def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)

if __name__ == '__main__':
    socketio.run(app, debug=True)


the client side code( the code we will send to browser when load the landing page index.html)

Step by step guide
First add the scoketuio client side library

<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Application Prototype</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    
</head>
<body>

    <script>

    </script>
</body>
</html>

Add html content to show the message and users key

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <h1>Python Scoketio Chat Prototype</h1>

<!--User unique key will be shows here -->
    <p>Your Unique Key: <span id="uniqueKey"></span></p>

<!--This is where user will enter the friends key to send message to friend -->
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>


<!-- This is where the send and received message will shown
    <div id="chat"></div>


<!-- This is where user will write the message
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>


    </script>
</body>
</html>

The logical part javascript

connect to socket io

const socket = io();

       const socket = io();
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
        });

When key sent by server this code will extract the key from data and place it to the html with the id name ‘uniquekey’

Initiate Chat

        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

this function will get key which user enter to start chat and send it to the another if that user is active

when the pervious user send the message other user will get it from client side with this code

       socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });

This will recieve the message from server and set it to the html chat div .

Start continuouis chat

if the user initiate chat . user can send countinous chat as long as the receiver is active

as friend key already stored when the initiate the chat. so user do not have to add the key every time when send message

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

The complete code javascript code for client side


    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>

The complete client side code (index.html)


<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Prototype With Socketio and Flask</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
    <h1>Private Chat Prototype With socketio and flask</h1>
    <p>Your Unique Key: <span id="uniqueKey"></span></p>
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>
    <div id="chat"></div>
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>
</body>
</html>



Structure

├── app.py
└── templates
    └── index.html

How you will test. it?

First run the code. and open the localhost link http://127.0.0.1:5000/ in the browser. Another one in in new incognito mode

So it will act like two unique user for your testing. Then Enter the other users unique key ( which works like unique username here) Then send message . Thats all. customize the code your necessary. Happy coding!

You can also get this project code from github
https://github.com/01one/flask-socketio-chat-application

Ajax example with flask

One of the best ajax applied in real world is username checker. In this example we will check if there is existing username

This is code /project we will

  • use ajax to search username
  • if username exist or does not exist send to message to the user
  • Also create new user with html form and flask if username exists

Our first step: Check if username exists or not

Imagine we have this existing username

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]

when the user enter a username we will check it from server(Check username)


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


When new account is created username will be added to the username list (Create New User)


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})


In the client side we are using jquery to make everything simpler.

When the user will type it will automatically send to server with ajax and return the response

We will also make sure if the username exists the response text will show in green color if not it will show in red color.


$(document).ready(function () {
	$('#username').keyup(function () {
		var username = $(this).val();
		if (username.length === 0) {
			$('#usernameMessage').text("");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/check_username',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
				if (response.message === 'Username is available!') {
					$('#usernameMessage').css('color', 'green');
				} else {
					$('#usernameMessage').css('color', 'red');
				}
			}
		});
	});




	$('#createProfileForm').submit(function (e) {
		e.preventDefault();
		var username = $('#username').val();
		if (username.length === 0) {
			$('#usernameMessage').text("Username cannot be empty.");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/create_profile',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
			}
		});
	});
});



The complete code

structure

├── app.py
└── templates
    └── username-id-generate.html

The serverside code


import re
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]


def is_valid_username(username):
	# Double check
	return re.match("^[a-zA-Z0-9_]*$", username) is not None


@app.route('/')
def index():
	return render_template('username-id-generate.html')


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})



if __name__ == '__main__':
	app.run(debug=True)



The client side code


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Profile</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            font-family: 'Helvetica Neue', sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #createProfileForm {
            background: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 350px;
        }
        h1 {
            text-align: center;
            font-size: 28px;
            margin-bottom: 20px;
            color: #333;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 16px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        #usernameMessage {
            color: red;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <form id="createProfileForm">
        <h1>Create Your Profile</h1>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" autocomplete="off" required>
        <span id="usernameMessage"></span>
        <input type="submit" value="Create Profile">
    </form>
    <script>
        $(document).ready(function () {
            $('#username').keyup(function () {
                var username = $(this).val();
                if (username.length === 0) {
                    $('#usernameMessage').text("");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
        $.ajax({
            type: 'POST',
            url: '/check_username',
            data: {'username': username},
            success: function (response) {
                $('#usernameMessage').text(response.message);
                if (response.message === 'Username is available!') {
                    $('#usernameMessage').css('color', 'green');
                } else {
                    $('#usernameMessage').css('color', 'red');
                }
            }
        });
    });

            $('#createProfileForm').submit(function (e) {
                e.preventDefault();
                var username = $('#username').val();
                if (username.length === 0) {
                    $('#usernameMessage').text("Username cannot be empty.");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
                $.ajax({
                    type: 'POST',
                    url: '/create_profile',
                    data: {'username': username},
                    success: function (response) {
                        $('#usernameMessage').text(response.message);
                    }
                });
            });
        });
    </script>
</body>
</html>



Get the project code from github

https://github.com/01one/flask-ajax-example

Build browser based Qr code generator with html css and javascript

The main features we will apply

User will able to paste link or text and generate the qr code

The dependency

We will use qurcodejs a javascript library for this

QR Code Generator

QR Code Generator

The complete code. Try and customize by yourself.


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>QR Code Generator</title>
  <style>
    input[type="text"] {
      width: 400px;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
      box-sizing: border-box;
    }

    #qr-code-button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
    }

    #qr-code-button:hover {
      background-color: #45a049;
    }

    #qr-code-image {
      margin-top: 30px;
      width: 200px;
      height: 200px;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      display: none;
    }
  </style>
</head>

<body>
  <div class="content">
    <h1>QR Code Generator</h1>
    <input type="text" id="qr-code-text-input" placeholder="Enter website URL or text">
    <button id="qr-code-button" onclick="generateQRCode()">Generate QR Code</button>
    <div id="qr-code-image"></div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/qrcode.min.js"></script>
  <script>
    var qrcode = null;
    function generateQRCode() {
      var text = document.getElementById('qr-code-text-input').value;
      if (text === '') return;
      if (qrcode !== null) {
        qrcode.clear();
        qrcode.makeCode(text);
      } else {
        qrcode = new QRCode(document.getElementById('qr-code-image'), { text: text, width: 400, height: 400 });
      }
      document.getElementById('qr-code-image').style.display = 'block';
    }
  </script>
</body>

</html>




Also you can get the code from github

https://github.com/01one/qr-code-generator-with-html-css-javascript

Create a Simple Image Gallery for Your Website (HTML, CSS & JavaScript)

Image Gallery

The essential structure of the gallery

  • The images will automatically fit to the display ( based on the image)
  • Show the image in smaller size first. Then When the user click the image it will show in larger scale

The complete code. Just place your image link in the img tag to show the image




<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<style>
  .gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 10px;
  }

  .image-wrapper {
    position: relative;
    overflow: hidden;
  }

  .zoomable {
    width: 100%;
    height: auto;
    object-fit: cover;
    cursor: pointer;
  }

  .full-image {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .full-image img {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
  }

  .close-button {
    position: absolute;
    top: 10px;
    right: 10px;
    color: white;
    font-size: 24px;
    cursor: pointer;
  }

  .nav-button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    font-size: 24px;
    cursor: pointer;
  }

  .prev-button {
    left: 10px;
  }

  .next-button {
    right: 10px;
  }
</style>
</head>
<body>

<div class="gallery">
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Hever_Castle_rose_garden_with_fountain.JPG/1280px-Hever_Castle_rose_garden_with_fountain.JPG" alt="Rose" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Missouri_Botanical_Garden_-_Seiwa-en.JPG/1280px-Missouri_Botanical_Garden_-_Seiwa-en.JPG" alt="Garden" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Singapore_Gardens_by_the_Bay_viewed_from_Marina_Bay_Sands_03.jpg/1280px-Singapore_Gardens_by_the_Bay_viewed_from_Marina_Bay_Sands_03.jpg" alt="Garden" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Monet_-_Impression%2C_Sunrise.jpg/1280px-Monet_-_Impression%2C_Sunrise.jpg" alt="Sunrise" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Rudolf_Reschreiter_Blick_von_der_H%C3%B6llentalangerh%C3%BCtte_zum_H%C3%B6llentalgletscher_und_den_Riffelwandspitzen_1921.jpg/1280px-Rudolf_Reschreiter_Blick_von_der_H%C3%B6llentalangerh%C3%BCtte_zum_H%C3%B6llentalgletscher_und_den_Riffelwandspitzen_1921.jpg" alt="" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="https://upload.wikimedia.org/wikipedia/commons/e/e3/Kheops-Pyramid.jpg" alt="Great_Pyramid_of_Giza" class="zoomable">
  </div>
</div>


<script>
  document.addEventListener('DOMContentLoaded', function () {
    const zoomableImages = document.querySelectorAll('.zoomable');
    let currentIndex = 0;

    zoomableImages.forEach(function (image, index) {
      image.addEventListener('click', function () {
        currentIndex = index;
        showFullImage(currentIndex);
      });
    });

    function showFullImage(index) {
      const fullImageContainer = document.createElement('div');
      fullImageContainer.classList.add('full-image');

      const fullImage = document.createElement('img');
      fullImage.src = zoomableImages[index].src;

      const closeButton = document.createElement('span');
      closeButton.classList.add('close-button');
      closeButton.innerHTML = '&times;';
      closeButton.addEventListener('click', function () {
        document.body.removeChild(fullImageContainer);
      });

      const prevButton = document.createElement('span');
      prevButton.classList.add('nav-button', 'prev-button');
      prevButton.innerHTML = '&#10094;';
      prevButton.addEventListener('click', function () {
        currentIndex = (currentIndex - 1 + zoomableImages.length) % zoomableImages.length;
        fullImage.src = zoomableImages[currentIndex].src;
      });

      const nextButton = document.createElement('span');
      nextButton.classList.add('nav-button', 'next-button');
      nextButton.innerHTML = '&#10095;';
      nextButton.addEventListener('click', function () {
        currentIndex = (currentIndex + 1) % zoomableImages.length;
        fullImage.src = zoomableImages[currentIndex].src;
      });

      fullImageContainer.appendChild(fullImage);
      fullImageContainer.appendChild(closeButton);
      fullImageContainer.appendChild(prevButton);
      fullImageContainer.appendChild(nextButton);
      document.body.appendChild(fullImageContainer);
    }
  });
</script>

</body>
</html>





You can also add image from the directory



<div class="gallery">
  <div class="image-wrapper">
    <img src="images/autumn.jpg" alt="Autumn" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="images/butterfly.jpg" alt="Butterfly" class="zoomable">
  </div>
  <div class="image-wrapper">
    <img src="images/horizon.jpg" alt="Horizon" class="zoomable">
  </div>

</div>




Get the Project code from github

https://github.com/01one/image-gallery-html-css-javascript

How to Make Analog Clock with HTML, CSS, and JavaScript

Simple Clock
12
3
6
9

The structure and the essentials

  • We need second , minute and hour hand,
  • second hand will circle through 360 degree every minute that means in every second it will move 6 degree
  • Minute hand moves 6 degree in every minute
  • And the hour hand moves 30 degree every hour

So we just add this logic in the clock that's it.

We get the time from browser


const now = new Date();

const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();




Then access the clock hand from JavaScript


const hourHand = document.getElementById('hour-hand');
const minuteHand = document.getElementById('minute-hand');
const secondHand = document.getElementById('second-hand');



Update the position based on the current time


const hourDeg = (hours % 12) * 30 + minutes / 2;
const minuteDeg = minutes * 6;
const secondDeg = seconds * 6;

hourHand.style.transform = `rotate(${hourDeg}deg)`;
minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
secondHand.style.transform = `rotate(${secondDeg}deg)`;


Add everything in a function also set interval of 1 second to update the clock every second


function updateClock() {
  const now = new Date();
  
  const hours = now.getHours();
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();

  // Analog clock
  const hourHand = document.getElementById('hour-hand');
  const minuteHand = document.getElementById('minute-hand');
  const secondHand = document.getElementById('second-hand');

  const hourDeg = (hours % 12) * 30 + minutes / 2;
  const minuteDeg = minutes * 6;
  const secondDeg = seconds * 6;

  hourHand.style.transform = `rotate(${hourDeg}deg)`;
  minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
  secondHand.style.transform = `rotate(${secondDeg}deg)`;

  // Digital clock
  const digitalClock = document.getElementById('digital-clock');
  digitalClock.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// Update the clock every second
setInterval(updateClock, 1000);

// Initial call to set the clock right away
updateClock();


The complete code


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Clock</title>
  <style>
    body {
      background-color: rgb(139, 126, 126);
    }
    .clock-container {
      color:#fffbe4;
      background-color: rgb(105, 96, 96);
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      font-family: Arial, sans-serif;
    }

    #analog-clock {
      border: 10px solid transparent;
      border-image: linear-gradient(to right, #b59d72, #ffe79a) 1;
      box-shadow: inset -1px 0px 12px 9px rgba(0, 0, 0, 0.5); 
      width: 300px;
      height: 300px;
      position: relative;
    }

    .clock-hand {
      box-shadow: 0 0 10px #00000080; 
      position: absolute;
      background:  linear-gradient(to right, #b59d72, #ffe79a);
      transform-origin: 50% 100%;
      width: 4px;
      top: 50%;
      left: 50%;
    }

    #hour-hand {
      height: 50px;
      margin-top: -50px;
    }

    #minute-hand {
      height: 70px;
      margin-top: -70px;
    }

    #second-hand {
      height: 80px;
      background:  linear-gradient(to right, #b59d72, #ffe79a);
      margin-top: -80px;
    }

    .hour-number-left-right {
      margin-top:-8px;
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }

    .hour-number-top-bottom {
      margin-left: -6px;
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }



    .hour-number {
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }

    .minute-dot {
      position: absolute;
      background-color: #333;
      width: 4px;
      height: 4px;
      border-radius: 50%;
    }

    #digital-clock {
      display: flex;
      position:absolute;
      margin-top:400px;
      font-size: 48px;
    }
  </style>
</head>
<body>
  <div class="clock-container">
    <div id="analog-clock">
      <!-- Clock Hands -->
      <div id="hour-hand" class="clock-hand"></div>
      <div id="minute-hand" class="clock-hand"></div>
      <div id="second-hand" class="clock-hand"></div>
      
      <!-- Hour Numbers -->
      <div class="hour-number-top-bottom" style="top: 10px; left: 50%;">12</div>
      <div class="hour-number-left-right" style="top: 50%; left: 95%;">3</div>
      <div class="hour-number-top-bottom" style="bottom: 10px; left: 50%;">6</div>
      <div class="hour-number-left-right" style="top: 50%; left: 5%;">9</div>

      <!-- Minute Dots -->
      <div class="minute-dot" style="top: 15%; left: 50%;"></div>
      <div class="minute-dot" style="top: 50%; left: 85%;"></div>
      <div class="minute-dot" style="bottom: 15%; left: 50%;"></div>
      <div class="minute-dot" style="top: 50%; left: 15%;"></div>
    </div>
    <div id="digital-clock"></div>
  </div>
  <script>
    function updateClock() {
      const now = new Date();
      
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();

      // Analog clock
      const hourHand = document.getElementById('hour-hand');
      const minuteHand = document.getElementById('minute-hand');
      const secondHand = document.getElementById('second-hand');

      const hourDeg = (hours % 12) * 30 + minutes / 2;
      const minuteDeg = minutes * 6;
      const secondDeg = seconds * 6;

      hourHand.style.transform = `rotate(${hourDeg}deg)`;
      minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
      secondHand.style.transform = `rotate(${secondDeg}deg)`;

      // Digital clock
      const digitalClock = document.getElementById('digital-clock');
      digitalClock.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    // Update the clock every second
    setInterval(updateClock, 1000);

    // Initial call to set the clock right away
    updateClock();
  </script>
</body>
</html>


Get the code from github
https://github.com/01one/analog-html-clock

How to get the mouse position in html

Knowing mouse position is essential if we want to apply some wonderful effect in our web application

We can get the mouse position from mousemove event.

In the example code we are using mousemove event. This will helps us go get the mouse coordinate in real-time

In the code you will get the mouse position in the browser console as we console.log the real-time coordinated.


<!DOCTYPE html>

<body>

<script>

    function currentMousePosition(event) {
        console.log(event.clientX, event.clientY);
    }

    document.addEventListener('mousemove', currentMousePosition);
</script>
</body>
</html>



    
    
    

In our first example code we got the mouse position. Now apply some wonderful effect in this..


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse Particle Effect</title>
    <style>
        .particle {
            position: absolute;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #f00;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <script>
        function FrequencyManagement(func, delay) {
            let lastCalled = 0;
            return function(...args) {
                const now = new Date().getTime();
                if (now - lastCalled < delay) {
                    return;
                }
                lastCalled = now;
                func(...args);
            };
        }

        function createParticle(x, y) {
            const particle = document.createElement('div');
            particle.classList.add('particle');
            particle.style.left = `${x}px`;
            particle.style.top = `${y}px`;
            particle.style.backgroundColor = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 5 + 2;
            const vx = Math.cos(angle) * speed;
            const vy = Math.sin(angle) * speed;

            let distance = 0;

            const updateInterval = setInterval(() => {
                x += vx;
                y += vy;
                distance += Math.sqrt(vx * vx + vy * vy);
                particle.style.left = `${x}px`;
                particle.style.top = `${y}px`;

                if (x < 150 || x > window.innerWidth - 150 || y < window.pageYOffset + 150 || y > window.innerHeight + window.pageYOffset - 150 || distance >= 100) {
                    clearInterval(updateInterval);
                    particle.remove();
                }
            }, 30);

            document.body.appendChild(particle);
        }

        function handleMouseMovement(event) {
            const x = event.clientX + window.pageXOffset;
            const y = event.clientY + window.pageYOffset;

            createParticle(x, y);
        }

        document.addEventListener('mousemove', FrequencyManagement(handleMouseMovement, 10));
    </script>
</body>
</html>

    
    
    

Get the code from github https://github.com/01one/web-browser-mouse-coordinate

Create Your First HTML Button: Simple Tutorial with Example

First We Will create the most simple button with html without any functionality. That means it will just show the button and do nothing..



<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button>Button</button>

</body>
</html>


    
    
    

From the code.

  • We set the button with button tag like this <button>Button Text</button>

This code is missing the functionality. That means we did not said the code when the user click on the button what should it do!

So in the next example we will add this functionality.

It will be like this. When the user click the button it will show this text “Hello User”



<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button id="HelloButton">Button</button>
<p id="message"></p>

<script>
  var exampleButton = document.getElementById('HelloButton');

  exampleButton.addEventListener('click', function() {
    var messageParagraph = document.getElementById('message');
    messageParagraph.innerHTML = 'Hello User';
  });
</script>

</body>
</html>





    
    
    

From The code

When the user click the button it triggers the JavaScript function and find the message id and include the text inside the paragraph tag.

In the Next Example We added some css of button.

Here the color means the font color

Now add some design in the button




<!DOCTYPE html>
<html>
<head>
  <style>

    #HelloButton {
      padding: 10px 20px;
      background-color: black;
      color:white;
      font-size: 16px;
    }

    #message {
      font-size: 18px;
      margin-top: 10px;
    }
  </style>
</head>
<body>

<button id="HelloButton">Button</button>
<p id="message"></p>

<script>
  var button = document.getElementById('HelloButton');
  var messageParagraph = document.getElementById('message');

  button.addEventListener('click', function() {
    messageParagraph.innerHTML = 'Hello User';
  });
</script>

</body>
</html>



    
    
    

Test the code here. Excersise the example instantly..

How to show html code inside html without rendering

We can show html inside html by using using the html entity
‘<‘ as ‘&lt;’ and the ‘&’ as ‘&amp;’

Normally we use like this in html .

<h1> This is H1 tag </h1>

But it the result renders html and shows like this

This is h1 tag

So will We will use this To prevent the rendering

&lt;h1&gt; This is H1 tag &lt;/h1&gt;

Now there is a full example which the demonstrations this

Copy the code and try by yourself.



<!DOCTYPE html>
<html>
<head>

</head>
<body>

<h1> This is H1 tag </h1>
&lt;h1&gt; This is also H1 tag &lt;/h1&gt;
    

</body>
</html>