JavaScript - Create Conversion Tool with HTML, CSS, and JavaScript

How to Create a Simple Unit Conversion App with JavaScript 


How to Create a Simple Unit Conversion App with JavaScript



In this Javascript tutorial, we will see how to create a conversion tool to convert values between different units (e.g., inches to centimeters, pounds to kilograms, Fahrenheit to Celsius) and displays the converted result.



Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>conversion Tool</title>

<style>

body{ background-color: #f5f5f5; font-family: 'Open Sans', sans-serif; color: #333; }

#conversion-tool{ background-color: #fff; border-radius: 5px; padding: 20px; max-width: 400px;
margin: 20px auto; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1)
}

form{ display: flex; flex-direction: column; }

label{ font-weight: bold; margin-bottom: 5px; }

input[type="number"]:focus, select:focus{ outline: none; }

input[type="number"], select{
border: 1px solid #ddd; border-radius: 3px; padding: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
margin-bottom: 10px; font-size: 16px; background-color: #f2f2f2;
}


/* add a drop icon to the select */
select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg width='12' height='6' viewBox='0 0 12 6'
xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0l6 6 6-6H0z' fill='%23333'
fill-opacity='0.4' fill-rule='evenodd'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 10px center;
padding-right: 25px;
}

button{ background-color: #333; color: #fff; border:none; border-radius: 5px;
padding: 10px 20px; cursor: pointer; transition: all 0.2s ease-in-out;
}

button:hover{ background-color: #555; }

#output{ font-weight: bold; font-size: 16px; margin-top: 25px; }

#output-value{ color: purple; }

</style>

</head>
<body>


<div id="conversion-tool">
<form>
<label for="input-value">Value to Convert:</label>
<input type="number" id="input-value" min="0">
<br>
<label for="from-unit">Convert From:</label>
<select id="from-unit">
<option value="inches">Inches</option>
<option value="centimeters">Centimeters</option>
<option value="pounds">Pounds</option>
<option value="kilograms">Kilograms</option>
<option value="fahrenheit">Fahrenheit</option>
<option value="celesius">Celesius</option>
</select>
<br>
<label for="to-unit">Convert To:</label>
<select id="to-unit">
<option value="inches">Inches</option>
<option value="centimeters">Centimeters</option>
<option value="pounds">Pounds</option>
<option value="kilograms">Kilograms</option>
<option value="fahrenheit">Fahrenheit</option>
<option value="celesius">Celesius</option>
</select>
<br>
<button type="button" id="convert-btn">Convert</button>
<p id="output">Converted Value:<span id="output-value"></span></p>
</form>
</div>

<script>

// This function gets called when the "Convert" button is clicked
function convert()
{
// Get the user's input value and selected units
const inputValue = document.getElementById("input-value").value;
const fromUnit = document.getElementById("from-unit").value;
const toUnit = document.getElementById("to-unit").value;

// Initialize the output value as the input value
let outputValue = inputValue;

// Check the selected units and perform the appropriate calculations
if(fromUnit === "inches" && toUnit === "centimeters"){
outputValue = inputValue * 2.54;
}
else if(fromUnit === "centimeters" && toUnit === "inches"){
outputValue = inputValue / 2.54;
}

else if(fromUnit === "pounds" && toUnit === "kilograms"){
outputValue = inputValue * 0.453592;
}

else if(fromUnit === "kilograms" && toUnit === "pounds"){
outputValue = inputValue / 0.453592;
}

else if(fromUnit === "fahrenheit" && toUnit === "celesius"){
outputValue = (inputValue-32) * (5/9);
}

else if(fromUnit === "celesius" && toUnit === "fahrenheit"){
outputValue = (inputValue * (9/5)) + 32;
}

// Update the output field with the converted value
document.getElementById("output-value").innerHTML = outputValue;
}

// Attach the "convert" function to the "Convert" button's click event
document.getElementById("convert-btn").addEventListener("click", convert);


</script>


</body>
</html>




Code Explanation:

this JavaScript code, allows users to convert values between different units and displays the converted result..

This JavaScript code performs the following actions:

1 - The code defines a JavaScript function called convert() that performs the unit conversion.

2 - It retrieves user input values (value to convert, source unit, and target unit) from the HTML form.

3 - The function then calculates the converted value based on the selected units.

4 - The result of the conversion is displayed on the webpage..



OUTPUT:

Create Conversion Tool with HTML, CSS, and JavaScript









Java - Create Dark Night Sky Animation

How to Create a Night Sky Animation with Stars and a Moon In Java Netbeans



In this Java Tutorial we will see How To Create a simple animated scene with stars moving across a dark night sky and a moon shining brightly. 
The animation gives the impression of a serene night with stars twinkling and a calm moon in the background.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



package new_tutorials;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 *
 * @author 1BestCsharp
 */
public class DarkNightSky extends JPanel{

    private static final int FRAME_WIDTH = 800;
    private static final int FRAME_HEIGHT = 600;
    private static final int NUM_STARS = 100;
    private static final int STAR_SIZE = 5;
    private static final int ANIMATION_DELAY = 50;
    
    private final List<Point> stars;  // List to store the positions of stars
    private final Moon moon;
    
    public DarkNightSky()
    {
       stars = new ArrayList<>();  // Initialize the list of stars
       generateStars();
       moon = new Moon();
       
       Timer timer = new Timer(ANIMATION_DELAY, (e) -> {
           
           moveStars();
           repaint();
           
       });
       
       timer.start();
    }
    
    
    // Generate random star positions within the panel bounds
    private void generateStars(){
        Random rand = new Random();
        for(int i = 0; i < NUM_STARS; i++){
            int x = rand.nextInt(FRAME_WIDTH);
            int y = rand.nextInt(FRAME_HEIGHT);
            stars.add(new Point(x, y));
        }
    }
    
    
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        // Fill the panel with a black background
        g.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
        g.setColor(Color.WHITE);
        
        // Draw stars as rectangles
        for(Point star : stars){
            g.fillRect(star.x, star.y, STAR_SIZE, STAR_SIZE);
        }
        
        // Draw the moon using the Moon class
        moon.draw(g);
        
    }
    
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Dark Night Sky");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.add(new DarkNightSky());
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    
    // Move stars in the animation, wrap around when reaching panel bounds
    private void moveStars(){
        
        for(Point star : stars){
            
            star.translate(1, 1);
            
            if(star.x > FRAME_WIDTH)
            {
                star.x = 0;
            }
            
            if(star.y > FRAME_HEIGHT)
            {
                star.y = 0;
            }
        }
        
    }
    
}

// Moon class to draw a white circle representing the moon
class Moon{
    
    private static final int MOON_RADIUS = 100;
    private static final int MOON_X = 600;
    private static final int MOON_Y = 100;
    
    // Draw the moon
    public void draw(Graphics g){
        g.setColor(Color.WHITE);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(MOON_X, MOON_Y, MOON_RADIUS, MOON_RADIUS);
    }
    
    
}


The Final Result:









Database Data Navigation in PHP

How to Navigate and Display Database Records Using PHP

How to Navigate and Display Database Records Using PHP


In this PHP tutorial, we will see how to to retrieve product information from a database and display it within an HTML form. 
Users can navigate through the products by using navigation buttons, and the form fields will dynamically update to show the details of the selected product.



Project Source Code:



<?php

// Connect to the database
require_once "db_connect.php";

// Define the SQL query to select all products from the "product" table
$query = "SELECT * FROM `product`";

// Prepare the SQL statement
$stmt = $conn -> prepare($query);

// Execute the SQL statement
$stmt->execute();

// Fetch all the results from the statement and store them in an array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the products
$products = array();

foreach( $results as $row ){
$product = array("id"=>$row["id"],
"name"=>$row["name"],
"price"=>$row["price"],
"image"=>$row["image"]
);

// Add the product array to the products array
array_push($products, $product);
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Data Navigation</title>
<style>

body{ font-family:Arial, sans-serif; background-color:#f2f2f2; }

form{ background-color:#fff; padding:20px; width:500px; margin: 25px auto;
border-radius:5px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
h1{ text-align:center; color:#333; margin-bottom:20px; }

.form-row{ margin:10px 0; }

input{ padding:10px; margin:10px 0; border:1px solid #ccc;
border-radius:4px; box-sizing:border-box; width:100%; }

button{ background-color:#4caf50; color:#fff; padding:10px 20px; border:none;
border-radius:4px; cursor:pointer; margin-top:10px; width:24%;
font-size:16px; }

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

#image{ display:flex; align-items:flex-start; }

#image label{ margin-right:10px; }

#image img{ margin:10px; width:50%; height:150px; border-radius:5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3); }

</style>
</head>
<body>

<form id="product-form">
<h1>Product Information</h1>
<div class="form-row">
<label for="product-id">ID:</label>
<input type="text" id="product-id" name="product-id">
</div>
<div class="form-row">
<label for="product-name">Name:</label>
<input type="text" id="product-name" name="product-name">
</div>
<div class="form-row">
<label for="product-price">Price:</label>
<input type="text" id="product-price" name="product-price">
</div>
<div class="form-row">
<div id="image">
<label for="product-image">Image:</label>
<img id="product-image" src="">
</div>
</div>
<div class="form-row">
<button type="button" id="btn-first">First</button>
<button type="button" id="btn-prev">Previous</button>
<button type="button" id="btn-next">Next</button>
<button type="button" id="btn-last">Last</button>
</div>

<script>

// convert the PHP array to a JavaScript object in JSON format.
const products = <?php echo json_encode($products); ?>

// Get the buttons
const btnFirst = document.getElementById('btn-first');
const btnNext = document.getElementById('btn-next');
const btnPrevious = document.getElementById('btn-prev');
const btnLast = document.getElementById('btn-last');

// Define a variable to keep track of the current index
let currentIndex = 0;

// Function to update the form fields based on the current index
function updateForm(){

const product = products[currentIndex];

document.getElementById('product-id').value = product.id;
document.getElementById('product-name').value = product.name;
document.getElementById('product-price').value = product.price;
document.getElementById('product-image').src = product.image;

}

// Function to handle button clicks
function handleButtonClick(e)
{
switch(e.target.id){
case 'btn-first':
currentIndex = 0;
break;
case 'btn-prev':
currentIndex = Math.max( currentIndex - 1, 0 );
break;
case 'btn-next':
currentIndex = Math.min( currentIndex + 1, products.length - 1 );
break;
case 'btn-last':
currentIndex = products.length - 1;
break;
default:
break;
}

updateForm();

}

// Add event listeners to the buttons
btnFirst.addEventListener('click', handleButtonClick);
btnNext.addEventListener('click', handleButtonClick);
btnPrevious.addEventListener('click', handleButtonClick);
btnLast.addEventListener('click', handleButtonClick);

// Initialize the form
updateForm();


</script>


</body>
</html>



Code Explanation:

PHP Section: This PHP code connects to a database using "db_connect.php," defines and executes an SQL query to select all products from a "product" table, fetches and stores the results in an array, and constructs an array of product information.

HTML/JavaScript Section: This code generates an HTML form with fields for product information.
It includes navigation buttons (First, Previous, Next, Last) to move between products and applies CSS styles.
JavaScript manages button clicks, updates form fields with product data, and keeps track of the current product.
listeners are added for button interaction, and the form is initialized through the updateForm function.



OUTPUT:


Database Data Navigation in PHP

Data Navigation in PHP




if you want the source code click on the download button below