Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Design a Student Grade Calculator using JavaScript
Next article icon

Temperature Converter using HTML CSS and JavaScript

Last Updated : 11 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see Temperature Conversion between Celsius, Fahrenheit & Kelvin using HTML CSS & JavaScript. The Temperature is generally measured in terms of unit degree., i.e. in degrees centigrade, in degrees, Fahrenheit & Kelvin.

  • Celsius is a standard unit of temperature on the Celsius scale, & is represented by the °C symbol.
  • Fahrenheit uses the degree Fahrenheit as the unit & is represented with the °F symbol.
  • Kelvin is an internationally recognized standard for scientific temperature measurement. It is an absolute temperature scale that is obtained by shifting the Celsius scale by −273.15°, in order to coincide the absolute zero to 0K.

Examples depict 0°C in Fahrenheit & Kelvin:

Input: 0 in Celsius
Output: 32 in Fahrenheit and 273.15 in Kelvin
Input: 0 in Fahrenheit
Output: -17.78 in Celsius and 255.37 in Kelvin
Input: 0 in Kelvin
Output: -273.15 in Celsius and -459.67 in Fahrenheit

Formula for converting Celsius scale to Fahrenheit scale and Kelvin scale:

T(°F) = (T(°C) * 9)/5 + 32
T(°K) = T(°C) + 273.15

Formula for converting Fahrenheit scale to Celsius scale and Kelvin scale:

T(°C) = ((T(°F) - 32) * 5) / 9
T(°K) = (T(°F) - 32) * 5 / 9 + 273.15

Formula for converting Kelvin scale to Celsius scale and Fahrenheit scale:

T(°C) = (T(°K) - 273.15
T(°F) = (T(°K) - 273.15) * 9 / 5 + 32;

Approach:

  • Create one container in which all the elements are present.
  • Inside this container add 3 input fields in which one for Celsius and another for Fahrenheit and Kelvin.
  • Now Style which you want I add this container in the center.
  • Now added Javascript which converts the following Temperature(Fahrenheit, Celsius, Kelvin) to the corresponding Remaining Two Temperature prints results in the various input fields.

Example: This example illustrates the basic temperature Conversion between Celsius, Fahrenheit & Kelvin using HTML, CSS & JS.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,initial-scale=1.0">

    <style>
        * {
            margin: 0;
            padding: 0;
            font-family:
                Verdana, Geneva, Tahoma, sans-serif;
        }

        .container {
            width: 100%;
            height: 100vh;
            background-image:
                linear-gradient(rgb(140, 219, 140),
                    rgb(20, 141, 20));
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .container h1 {
            color: green;
            font-weight: 700;
            font-size: 25px;
            text-align: center;
        }

        .converter-row {
            display: flex;
            width: 40%;
            justify-content: space-between;
            align-items: center;
            background: rgb(0, 56, 0);
            border-radius: 10px;
            padding: 50px 20px;
        }

        .col {
            flex-basis: 32%;
            text-align: center;
        }

        .col label {
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 10px;
            color: #fff;
        }

        .col input {
            width: 150px;
            height: 30px;
            background: white;
            border-radius: 5px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>GeeksforGeeks <br>
            Temperature Converter</h1>
        <div class="converter-row">
            <div class="col">
                <label>Fahrenheit</label>
                <input type="number" id="fahrenheit">
            </div>

            <div class="col">
                <label>Celsius</label>
                <input type="number" id="celsius">
            </div>

            <div class="col">
                <label>Kelvin</label>
                <input type="number" id="kelvin">
            </div>
        </div>
    </div>

    <script>
        let celsius =
            document.getElementById('celsius');
        let fahrenheit =
            document.getElementById('fahrenheit');
        let kelvin =
            document.getElementById('kelvin');
        celsius.oninput = function () {
            let f = (parseFloat(celsius.value) * 9) / 5 + 32;
            fahrenheit.value = parseFloat(f.toFixed(2));

            let k = (parseFloat(celsius.value) + 273.15);
            kelvin.value = parseFloat(k.toFixed(2));
        }
        fahrenheit.oninput = function () {
            let c = ((parseFloat(
                fahrenheit.value) - 32) * 5) / 9;
            celsius.value = parseFloat(c.toFixed(2));

            let k = (parseFloat(
                fahrenheit.value) - 32) * 5 / 9 + 273.15;
            kelvin.value = parseFloat(k.toFixed(2));
        }
        kelvin.oninput = function () {
            let f = (parseFloat(
                kelvin.value) - 273.15) * 9 / 5 + 32;
            fahrenheit.value = parseFloat(f.toFixed(2));

            let c = (parseFloat(kelvin.value) - 273.15);
            celsius.value = parseFloat(c.toFixed(2));
        }
    </script>
</body>

</html>

Output:


Next Article
Design a Student Grade Calculator using JavaScript
author
priyansh70890
Improve
Article Tags :
  • Project
  • JavaScript
  • Web Technologies
  • JavaScript-Projects

Similar Reads

    HTML Calculator
    HTML calculator is used for performing basic mathematical operations like Addition, subtraction, multiplication, and division.You can find the live preview below, try it: To design the basic calculator, we will use HTML , CSS , and JavaScript . HTML is used to design the basic structure of the calcu
    3 min read
    JavaScript Calculator
    To build a simple calculator using JavaScript, we need to handle basic arithmetic operations such as addition, subtraction, multiplication, and division. JavaScript, along with HTML and CSS, is commonly used to create interactive web-based calculators.What We Are Going to CreateWe will build a simpl
    7 min read
    JavaScript Scientific Calculator
    The HTML Scientific Calculator is a tool for performing advanced scientific calculations like finding exponents, logarithms, factorials, and more. This calculator comprises two sections: the input section, where the user types in their mathematical problem, and the output screen, which displays all
    4 min read
    JavaScript Neumorphism Effect Calculator
    In this article, we will learn how to create a working calculator with the Neumorphism effect using HTML, CSS, and JavaScript. Basic mathematical operations such as addition, subtraction, multiplication, and division can be performed using this calculator. Approach: Neumorphism is a contemporary app
    3 min read
    JavaScript Age Calculator
    In the Age Calculator, the user enters their date of birth using a date input field. The tool calculates and displays the exact age in years, months, and days from the current date (or a specified date). We'll design the layout using HTML and CSS, and add functionality using JavaScript. It will also
    3 min read
    JavaScript Tip Calculator
    The tip is the money given as a gift for good service to the person who serves you in a restaurant. In this project, a simple tip calculator is made that takes the billing amount, type of service, and the number of persons as input. As per the three inputs, it generates a tip for the serving person.
    4 min read
    JavaScript Geometry Calculator
    In this article, we will see how to design a Geometry Calculator using HTML, CSS, and JavaScript. A Geometry calculator is used to calculate the area and parameters of different shapes and figures, like circles, rectangles, squares, triangles, etc. This can be helpful in cases where one wants to cal
    4 min read
    JavaScript Aspect Ratio Calculator
    In this article, we are going to implement an aspect ratio calculator. An aspect ratio calculator proves to be a useful tool for individuals seeking to determine the proportions of images or videos based on their width and height. Our aspect ratio calculator has a live preview option that enables us
    5 min read
    JavaScript Binary Calculator
    HTML or HyperText Markup Language along with CSS (Cascading Stylesheet) and JavaScript can be used to develop interactive user applications that can perform certain functionalities. Similarly, a binary calculator can be developed using HTML, CSS, and JS altogether. Binary Calculator performs arithme
    5 min read
    JavaScript Percentage Calculator
    The percentage calculator is useful for students, shopkeepers, and for solving basic mathematical problems related to percentages. In this article, we are going to learn, how to make a percentage calculator using HTML CSS, and JavaScriptFormula used:What is X percent of Y is given by the formula: X
    3 min read
    JavaScript Profit and Loss Calculator
    In this article, we will create a profit & loss calculator using HTML, CSS & Javascript for adding the basic functionality along with adding the design and layout. Profit and Loss Calculator is basically used to calculate the amount or percentage received after selling a particular price or
    3 min read
    JavaScript BMI Calculator
    A BMI (Body Mass Index) Calculator measures body fat based on weight and height, providing a numerical value to categorize individuals as underweight, normal weight, overweight, or obese. It’s widely used to assess health risks and guide lifestyle or medical decisions.A BMI Calculator using JavaScri
    3 min read
    JavaScript Temperature Calculator
    In this article, we will see Temperature Conversion between Celsius, Fahrenheit & Kelvin using HTML CSS & JavaScript. The Temperature is generally measured in terms of unit degree., i.e. in degrees centigrade, in degrees, Fahrenheit & Kelvin. Celsius is a standard unit of temperature on
    3 min read
    JavaScript Student Grade Calculator
    A Student Grade Calculator is a tool used to compute students' grades based on their scores in various assessments, such as assignments, quizzes, exams, or projects. It helps standardize grading, ensures accuracy, and provides students with a clear understanding of their academic performance.Formula
    4 min read
    JavaScript Loan Calculator
    The Loan Calculator can be used to calculate the monthly EMI of the loan by taking the total amount, months to repay, and the rate of interest.Formula Used:interest = (amount * (rate * 0.01))/months;total = ((amount/months) + interest);ApproachExtract values from HTML input elements (#amount, #rate,
    2 min read
    JavaScript Interest Calculator
    Simple Interest is the term used to describe the rate at which money is borrowed or lent. Simple Interest Calculator serves as a practical tool for computing interest on loans or savings without compounding. It allows you to determine the simple interest on the principal amount, offering flexibility
    3 min read
    JavaScript CGPA Calculator
    Nowadays, colleges use grades like A, B, C, D, and F, and assign credits to courses. In this calculator, you just need to input your subject name, grade, and credit. We'll also include options to update or delete information in case of mistakes. This way, you won't have to re-enter all details if yo
    4 min read
    JavaScript Bartletts Test Calculator
    In this article, we are going to implement Bartlett's test calculator in JavaScript. Bartlett's test is a statistical test used to determine whether the variances of multiple groups are homogeneous and plays a crucial role in various fields of experimental research such as analysis of variance and h
    3 min read
    JavaScript Unit Converter
    In this article, we will be developing an interactive and styled unit converter using HTML, CSS, and JavaScript.In this application, we have a select category option box in which different types of units are specified, like temperature, area, weight, length, and time. As per the user selection, the
    7 min read
    JavaScript Length Converter
    In this article, we will learn how to create a length converter using HTML, CSS, and JavaScript. The Length Converter is an intuitive web-based application that eliminates the complexities associated with manual conversions. Its user-friendly interface allows users to input a numerical value and sel
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences