How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice ***

I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the box to simply disappear by setting the opacity to 0, but I would prefer a smoother fade out transition. I know that adjusting the opacity in small increments over time is necessary, but despite my efforts of searching online and experimenting with various approaches, I can't seem to get it right. Any guidance from someone patient would be highly appreciated. My goal is to have the .js file execute this function like the other buttons in my project. It would also be great if clicking the button twice could trigger a fade out followed by a fade back in. I'm interested in learning how one button can produce an effect and then reverse it. I've included two snippets below, one from my .html file and the other from my .js file.

Thank you.

      function fadeInOutFunction(id){
    document.getElementById("box").style.opacity = 0;
  }

  function blueFunction(id){
    document.getElementById("box").style.backgroundColor = "blue";
    document.getElementById("box").style.opacity = 1;
  }

  function pinkFunction(id){
    document.getElementById("box").style.backgroundColor = "pink";
    document.getElementById("box").style.opacity = 1;
  }

  // Add more color functions as needed

  function resetFunction(id){
    document.getElementById("box").style.opacity = 1;
    document.getElementById("box").style.height = "250px";
    document.getElementById("box").style.width = "250px" ; 
    document.getElementById("box").style.backgroundColor = "orange";
    document.getElementById("box").style.margin = "25px";
  }
        
        
        
        
<!DOCTYPE html>
<html>
<head>
    <style>
        #large22px {
    font-size: 22px;
    }
    </style>
    <title>JavaScript Funland</title>
</head>
<body>

    <p id="large22px">Click the buttons to modify the box:</p>

    <div id="box" style="height:250px; width:250px; background-color:orange; margin:25px"></div>

    <button id="fadeInOutFunction" onclick="fadeInOutFunction()">Fade In/Out</button>
    <button id="resetFunction" onclick="resetFunction()">Reset</button>
    <br>
    <br>
    <button id="blueFunction" onclick="blueFunction()">Blue</button>
    <button id="pinkFunction" onclick="pinkFunction()">Pink</button>
    // Include additional color buttons here

    <script type="text/javascript" src="Javascript.js"></script>
    
</html>

Answer №1

Striving for elegance may not always be the most direct approach to achieving a desired outcome. It's essential to focus on your objectives and then construct the logic needed to reach them. Feel free to ask if you have any questions.

An observation you'll make is that the checkStatus function is invoked in each action. Within this function, the status of the action is initially stored in a variable (status), which is checked with every click. For instance, pressing widen will save "widen" as the status in this variable so that subsequent clicks can either reset values or perform other actions accordingly.

var status = "";

function growFunction(id){
    let height; 
    if(checkStatus("grow")){
      height="250px"
    }else{
      height="350px"
    }
    document.getElementById("box").style.height = height;
    document.getElementById("box").style.opacity = 1;
  }

// The rest of the JavaScript functions remain unchanged

function checkStatus(x){
  if(status != "" && status != x){
    status = x;
    return false;
  }else{
    if(status==x){
      status = ""
      return true;
    }else{
      status = x;
      return false;
    }
  }
}
<!DOCTYPE html>

<head>
    <style>
        #large22px {
    font-size: 22px;
    }
    </style>
    <title>Jiggle Into JavaScript</title>
</head>
<body>

    // Buttons and box HTML code remains unchanged 

    <script type="text/javascript" src="Javascript.js"></script>
    

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

Utilizing Array Elements to Populate the Title Attribute in <TD> Tags

I am trying to display text on hover of a cell in my dynamically created HTML table, using the title attribute. However, instead of reading the contents of the array, it is displaying the array name as a string. Below is the code for generating the table ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

Tips for preventing special characters from being entered into a Kendo grid input column

Is there a way to prevent users from entering special characters into the description column of my Kendo grid? The column field setup is as follows: { field : "myDesc", width : 200, title : "My Description"} I have attempted the following approach so far ...

Transforming hover interactions into onclick events involves adjusting the CSS and JavaScript

Is there a way to convert this hover menu into an onclick menu? <div id='cssmenu'> <ul> <li class='has-sub'><a href='#'><span>Users</span></a> <ul> ...

Received an error while attempting to install react-router-dom

I keep encountering this error message whenever I try to install react-router-dom using NPM in VS Code: https://i.sstatic.net/hFshb.png npm ERR! Unexpected end of JSON input while parsing near '...stack-launcher":"^1.0' npm ERR! You can find ...

Launching Node Application

While working with NestJS and IIS, I encountered an issue when deploying my 'dist' folder on the server using IISNode. The error message 'module not found @nestjs/core' prompted me to install the entire 'package.json' files (n ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Is there a way to use jQuery draggable to move a zoomed image within a div clipping mask?

Looking to enhance user experience, I am developing an interface that allows users to zoom in on an image and move the zoomed version within a clipping mask div. I have created a div with dimensions of 200px by 200px and set overflow: hidden. Then, I inse ...

Discovering the names of files in a directory with Angular

Looking for a solution in Angular JS within a ModX app to retrieve file names from the gallery package every time it is updated. Is there a way to achieve this using Angular? I've been searching for Javascript solutions to this issue, but most of the ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

What assistance is available for building a JavaScript package that integrates and utilizes all necessary dependencies?

I am looking for a solution to include a third-party library in a JavaScript file that will be downloaded to our project only when we visit a specific page. This library is installed with npm and I want it to be part of the js package without includi ...

jQuery Mobile elements remain resident in the memory

I'm currently working on a jQuery mobile app that includes a chart created with Highcharts, which can be exported using CanVG and canvas2ImagePlugin. However, I've noticed that the chart object remains in memory. As a result, if the page is opene ...

What are some tips for getting media queries to function properly?

I need help with my homepage banner image as I am trying to make it responsive by adding media queries. The goal is for the image to adapt to 3 different sizes based on the screen being used, but currently only the medium-sized version appears. Could someo ...

Scraping a few URLs with Javascript for Web Data Extraction

I'm struggling to retrieve data from multiple URLs and write it to a CSV file. The problem I'm facing is that the fetched data is not complete (I expect 10 items) and it's not in the correct order. Instead of getting 1, 2, 3 sequentially, I ...

Vuetify alters the text color of the <vs-button> element

Outline of the Issue Upon installing vuetify, the text color of my <vs-button> has changed from white to black. Despite trying to adjust the color in the vuetify theme, I am unable to change it back. I have also created a custom filter rule using po ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

Necessary Selection from Dropdown

I've created a contact form with both optional and required fields. One of the mandatory fields is a drop-down menu, which looks like this: <div> <select name="favFruit[]" size="1" required> <option value="apple">Apple&l ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

Retrieving JSON data from a form in a Node.js application

Situation : Here is the HTML code I am working with <form action="http://example.com/nodejs/endpoint" method="post" enctype="multipart/form-data"> <label> Select JSON file <input type="file" name="json"> ...