Fading effect malfunctioning

I created a basic CSS box and am attempting to fade it by adjusting its opacity dynamically using the setInterval object.

Click here for the code on jsFiddle

CSS

#box {
margin:0px auto;
margin-top:10px;
height:50px;
width:50px;
background:black;
}

JAVASCRIPT

var fade;
function select(id) {
    return document.getElementById(id);
}
function disBox() {
    fade=setInterval(function(){
        select("box").style.opacity-=0.1;   
    },300);
    if (select("box").style.opacity==0) {
        clearInterval("fade");
        select("box").style.display="none";
    }   
    else {
        select("box").style.display="block";    
    }
}

The issue arises when the "-=" operator starts subtracting the opacity from 0 rather than 1. I'm seeking clarification on why this behavior occurs. Can someone provide an explanation?

Answer №1

Make sure to place your check regarding the opacity inside the loop.

function findElement(id) {
    return document.getElementById(id);
}


// Execute on page load
window.onload = function () {
    // Define initial variables
    var element = findElement('box'), opacity = 1, interval;

    // Start looping
    interval = setInterval(function(){
        // Update and apply opacity changes
        opacity = Math.max( 0, opacity - 0.1 );
        element.style.opacity = opacity;

        // Stop the loop when the element is no longer visible
        if ( !opacity )
            clearInterval(interval);
    },30);
};

Demo: http://jsfiddle.net/5gqRR/8/

Answer №2

It's not possible to assign an onload event directly to a div element. Instead, you can achieve this by implementing the following code:

XHTML

<div id="container"></div>

JavaScript

var fadeEffect;
function getElement(id) {
    return document.getElementById(id);
}
function toggleBox() {
    fadeEffect = setInterval(function(){
        getElement("container").style.opacity -= 0.1;    
    },300);
    if (getElement("container").style.opacity == 0) {
        clearInterval("fadeEffect");
        getElement("container").style.display = "none";
    }    
    else {
        getElement("container").style.display = "block";    
    }
}

window.onload = (function() {
    toggleBox();
})();

View the Demo

Additional Step

getElement("container").style.opacity = 1;  // Include this line to set initial opacity value
fadeEffect = setInterval(function(){
            getElement("container").style.opacity -= 0.1;    
        },300);

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

I'm struggling to make a div stretch across the full width of the screen

Despite my efforts, I can't seem to eliminate the noticeable margin between the div and the edges of the screen. <!DOCTYPE html> <html> <head> <title>Test2</title> <link rel="stylesheet" href="https://maxc ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

It seems that CSS shadows are working perfectly on Firefox and Chrome, but unfortunately, they are not displaying on

I have encountered an issue where CSS shadows appear fine on Firefox and Chrome, but do not display in Internet Explorer. Below is the code I am using: -moz-box-shadow: 0 0 20px #000; Can anyone provide a solution for this compatibility problem? Thank ...

Issue encountered: A TypeError was thrown indicating that variable 'b' is not a function within a nodejs(e

I recently installed the gentelella template using npm package manager and am facing an issue while trying to integrate the PNotify script. I have included the necessary CSS at the top of the file and added the script tags like this: <!-- jQuery --> ...

Issues with displaying markers on Google Maps API using JSON and AJAX

I have successfully coded the section where I retrieve JSON markers and loop through them. However, despite this, the markers do not seem to be appearing on the map. Could someone please assist me in identifying the mistake? $.ajax({ url ...

Content that can be scrolled within a React.Box container

I am struggling with a particular view. The columnBox I have can potentially hold a large number of items, but for some reason it's not scrolling in the view. I've already tried setting overflowY to auto, but since I don't know the exact hei ...

To enhance the user experience and improve performance, I will be implementing pagination on this page to efficiently display a dynamically generated set of elements

Currently working with CodeIgniter, where I am uploading a file into the database. Now, upon clicking a button, I wish for that file to be downloadable on the front end. ...

Create a resizable textarea within a flexbox container that allows for scrolling

Hey there! I'm struggling with a Flexbox Container that has three children. The first child contains a textarea, but it's overflowing beyond its parent element. Additionally, I want to make the content within child 2 and 3 scrollable. I've ...

The header does not appear to be responding to CSS floats

I am currently designing a header that includes a brand logo and a navigation menu. The header is nested within a div called container, and the HTML markup looks like this - <div class="container"> <div class="head"> ...

Ways to showcase information within the Uppy Dashboard Modal

My clients have requested for a custom button and message to be displayed within the Uppy DashboardModal, but I am facing difficulties in implementing this. Can someone please assist me with this? <DashboardModal uppy={uppy} id={this.prop ...

Issue with EnumDeserializer in jackson-mapper 1.9.12 version

I'm currently working on a scenario where I need to map a String to an enum Object using the Jackson ObjectMapper.readValue(String,Class) API. The issue arises when my JSON string contains a Task Object with an Action enum defined as follows: public ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

What methods can I implement to showcase random images in JavaScript using a JSON array value?

I am currently working on a fun avatar generator project. The challenge I'm facing is that each hairstyle consists of two parts (front and back), and when loaded randomly, the colors don't always match. To tackle this issue, I have organized the ...

Update the overflow property to overflow-auto instead of overflow-visible when the element exceeds the size of the viewport

I am facing an issue with my Angular component that opens another component as an offcanvas: openTop() { this.offcanvasService.open(AdvancedSearchComponent, { position: 'top', backdropClass: 'bg-dark', panelClass ...

Retrieving data from a material-ui Button component in a React application

I'm currently working with a function that looks like this: handleChangeButton = (e) => { alert(e.target.value) this.props.setFieldValue('degreeLevel', e.target.value); } Within my component's render function, I have the ...

Button-controlled automated presentation

I have devised a method to create an automatic slideshow using JavaScript. However, I am looking to incorporate manual control buttons as well. After adding manual control code, the slideshow seems to be malfunctioning. The provided code below is used for ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

Transitioning from Bootstrap 4 to Bootstrap 5 raises concerns about container compatibility

Interested in transitioning from Bootstrap 4 to Bootstrap 5. Noticed that the container max-width appears different on the default setting. Any insight on why this is and how it can be adjusted to resemble Bootstrap 4? I'm a beginner with Bootstrap, s ...