JS if clause fails to return true as expected

Here is my setup:

<div id="user_input">...</div>

And a button:

<input type="button" id="panel_button">...</button>

Using a selector:

function $(id) {
    return document.querySelector(id);
}

With an event handler:

var button_panel = $('#panel_button');
button_panel.addEventListener('click', fadeUserInputPanel, false);

Additionally, I have implemented 3 functions for fading the input panel in and out:

var user_input_panel = $('#user_input');
user_input_panel.style.opacity = 1;

function fadeUserInputPanel()
{
    if(user_input_panel.style.opacity == 1)
    {
        fade_out();
    } 
    else if(user_input_panel.style.opacity == 0)
    {
        fade_in();
    }
}

function fade_out() 
{
    if(user_input_panel.style.opacity > 0) 
    {
        user_input_panel.style.opacity -= 0.1;
        setTimeout(fade_out, 50);
    }
}

function fade_in() 
{
    if(user_input_panel.style.opacity < 1) 
    {
        user_input_panel.style.opacity += 0.1;
        setTimeout(fade_in, 50);
    }
}

However, there seems to be an issue:

Upon loading the page, the input panel is visible due to its opacity value of 1.

When clicking the panel_button, the input panel begins to fade out smoothly until it disappears.

But upon clicking the panel_button again to make the panel fade in, it only reaches an opacity of 0.1 and doesn't progress further.

Although the 'fade_in()' function should continue fading the panel in when the opacity is less than 1, it seems to be failing in this scenario. What could be causing this issue?

Answer №1

The reason behind this phenomenon is that the style.opacity property is considered a string and not a number.

> document.body.style.opacity = 0
0
> document.body.style.opacity 
"0"
> document.body.style.opacity += 0.1 
"00.1"
> document.body.style.opacity += 0.1 
"0.10.1"
> document.body.style.opacity += 0.1 
"0.10.1"

Although the subtraction in fade_out() function works fine, it is due to the fact that the -= operator does not perform string concatenation and always converts the arguments to numbers.

To resolve this issue, it is recommended to manually convert the opacity to a number:

function fade_in() {
    var opacity = +user_input_panel.style.opacity;
    if (opacity < 1) {
        user_input_panel.style.opacity = opacity + 0.1;
        setTimeout(fade_in, 50);
    }
}

Answer №2

To resolve the issue with opacity, you can use the parseFloat method to ensure it is properly handled.

function fadeIn() 
{
    if(panel.style.opacity < 1) 
    {
        panel.style.opacity = parseFloat(panel.style.opacity) + 0.1;
        console.log(panel.style.opacity);
        setTimeout(fadeIn, 50);
    }
}

For a live demonstration, check out this example: https://jsfiddle.net/janedoe/8dbh5f3r/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

varying perspectives in different browsers within my React application

I'm experiencing inconsistencies in the appearance of my website when viewed on Chrome mobile compared to Safari on an actual phone. Despite using prefixes for all my styles (WebKit, etc.) and incorporating normalize.css to address any issues, the dis ...

Having trouble getting Tailwind CSS to work with React components?

I'm having trouble getting Tailwind CSS to work properly. I've made sure to update to the latest version, but for some reason Tailwind is not functioning and there are no errors showing up in the console. Here is a link to my header component an ...

Could someone explain why the window.onload function is not functioning as expected on my other Vue page?

I am facing an issue with my two pages or "views" that have identical JS code. Both pages have a window.onload function where I perform some actions: console.log("loading") window.onload = function() { console.log("loaded") // do stuff } The problem is t ...

What is the correct way to establish a backgroundImage path in React JS?

When adding an img, the image path functions as expected: import Background from "./img/bg.webp"; ... <div> <img className='bg' src={Background} /> </div> However, when using the same path for the backgroundImage property, ...

Creating Table Rows on-the-fly

Seeking assistance and guidance from the community, I have modified code from an online tutorial to allow users to dynamically add rows to a table when data is entered in the row above. However, I am facing an issue where I can only insert one additional ...

CSS - Placeholder styling not being effective when selectors are grouped

Why is Chrome successful at executing this code: .amsearch-input::-webkit-input-placeholder { color: red; } <input class="amsearch-input" placeholder="It works!" /> ...while it doesn't work in other browsers: .amsearch-input::-we ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

Endless jasmine timeout

This question is a continuation of a discussion on the Remove timeout for single jasmine spec GitHub issue. Query: Can a single test be configured to never time out? The Issue: While it's possible to set a global timeout value using DEFAULT_TIMEOU ...

Storing a photo taken with a camera to a local directory on the computer

Currently, I am utilizing HTML5 inputs to capture a picture from the camera by using the code below: <input id="cameraInput" type="file" accept="image/*;capture=camera"></input> Subsequently, I am obtaining the image in blob format and manip ...

Jest - experiencing intermittent test failures on initial run, yet succeeding on subsequent runs

Writing tests with jest and supertest npm on a node server has been a challenge for me. When I try to run all the tests together, some of them fail inexplicably: https://i.sstatic.net/TWDVp.png However, if I selectively run only the failed tests in the t ...

Where will the user's input be stored?

Consider the following HTML code: <div class="form-group"> <label class="col-md-3 col-xs-3 col-sm-3 control-label">Phone</label> <div class="col-md-4 col-xs-4 col-sm-4"> <input id="input ...

The process of sending a POST parameter to a page in PHP and opening it

When attempting to open a page using PHP, such as: $html = file_get_contents('https://hammihan.com/search.php'); I encountered an issue where the page was being redirected to https://hammihan.com/users.php due to an empty input for name. To addr ...

Inserting line breaks in the data retrieved through AJAX

Utilizing ajax to transfer data from a sophisticated custom field wysiwyg editor. Within the markup provided, I am specifically addressing the div with the 'bio' class. However, upon receiving the data, it is consolidated into one large paragraph ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

The appearance of an SVG image inside an absolutely positioned div varies between Firefox and Chrome

The web page I am working on can be found at the following link: This webpage consists of text and SVG images, with the hex bolts positioned over specific areas of the text. Achieving this effect requires absolute positioning within a relatively positione ...

Could you explain the distinction between push and offset within the grid system?

I'm currently diving into the world of Bootstrap grids and trying to wrap my head around the concepts of push and offset. In the showcase below, I have two rows that only differ in how the third column is positioned - one using a push and the other an ...

The SyntaxError message indicates that there was an unexpected non-whitespace character found after the JSON data when parsing it

I received an Error message: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data Here is the code snippet: <script> $(document).ready(function () { $('.edit1').on('change', function () { ...

Looking for a resolution? Ensure that actions are plain objects by employing custom middleware specifically designed for managing asynchronous actions

I'm attempting to replicate a MERN stack project named Emaily, but I've encountered an error Error: Actions must be plain objects. Use custom middleware for async actions. Here is the code for my Action: import axios from 'axios'; im ...

What causes Windows 7 users to consider the VS Code website unsafe?

What causes Windows 7 users to view the VS Code website as unsafe? Visit the image link here ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...