Create a Fully Functional JavaScript Calculator with Dark/Light Mode & Scientific Function


In this project, I built a modern calculator that supports:

  • Basic arithmetic (+, -, *, /)
  • Scientific operations (sin, cos, tan, log, √, ^)
  • Dark/Light mode toggle
  • Responsive design for mobile devices
    This blog explains the HTML structure, CSS styling, and JavaScript logic step by step.

HTML Structure:

Enter fullscreen mode

Exit fullscreen mode

CSS Styling

  • Flexbox Centering: The calculator is centered vertically and horizontally.
  • Dark/Light Mode: .color class toggles background color.
  • Grid Layout: Buttons are arranged in a grid using grid-template-columns: repeat(4, 1fr).
  • Responsive: Media queries resize buttons and container on mobile screens.
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
#container {
    box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    display: flex;
    flex-direction: column;
    gap: 25px;
    padding: 30px;
    width: 25%;
    border-radius: 40px;
}
.gridbtn {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}
Enter fullscreen mode

Exit fullscreen mode

1.Selecting Elements
const input = document.getElementById("input");
const sci = document.getElementById("bottomBtn");

  • input → To display numbers and results.
  • sci → Reference to scientific buttons section.

2. Adding Values
Appends the clicked button value to the input field.
function press(value) {
input.value += value;
}

3. Clearing Input
Resets the input field when C button is clicked.
function clearInput() {
input.value = " ";
}

4. Calculating Expression

  • Evaluates the expression in the input field using eval().
  • If invalid input, displays “Error”.
function calculate() {
    try {
        input.value = eval(input.value);
    } catch {
        input.value = "Error";
    }
}
Enter fullscreen mode

Exit fullscreen mode

5. Dark/Light Mode Toggle

  • Toggles .color class for background change.
  • Changes heading color for readability.
function toggleDark() {
    document.getElementById('container').classList.toggle("color");
    document.getElementsByTagName('h1')[0].classList.toggle("h1");
}
Enter fullscreen mode

Exit fullscreen mode

6. Scientific Mode Toggle
Shows/hides scientific buttons (sin, cos, tan, etc.)

function scientific() {
    sci.style.display = sci.style.display === "none" ? "grid" : "none";
}
Enter fullscreen mode

Exit fullscreen mode

Thanks for reading! See you soon!



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *