What is preventing this code from successfully altering the opacity of an element based on its id?

I'm curious as to why the element's opacity is not temporarily reduced when the corresponding button is pressed. Any assistance would be greatly appreciated.

function pause(miliseconds) {
  var currentTime = new Date().getTime();

  while (currentTime + miliseconds >= new Date().getTime()) {}
}

function fadeOutFadeIn(ev) {
  document.getElementById(ev).style.opacity = '0.16';
  pause(1500);
  document.getElementById(ev).style.opacity = '1';
}
<div id="epicenter">
  <img src="https://via.placeholder.com/45/000" alt="Black" id="black">
  <img src="https://via.placeholder.com/45/00f" alt="Blue" id="blue">
  <img src="https://via.placeholder.com/45/0f0" alt="Green" id="green">
  <img src="https://via.placeholder.com/45/ddd" alt="Grey" id="grey">
  <img src="https://via.placeholder.com/45/a0d" alt="Purple" id="purple">
  <img src="https://via.placeholder.com/45/e73" alt="Orange" id="orange">
  <img src="https://via.placeholder.com/45/f00" alt="Red" id="red">
  <img src="https://via.placeholder.com/45/ff0" alt="Yellow" id="yellow">
  <img src="https://via.placeholder.com/45/fcc" alt="Pink" id="pink">
</div>
<button onclick="fadeOutFadeIn('black')">black</button>
<button onclick="fadeOutFadeIn('blue')">blue</button>
<button onclick="fadeOutFadeIn('green')">green</button>
<button onclick="fadeOutFadeIn('grey')">grey</button>
<button onclick="fadeOutFadeIn('purple')">purple</button>
<button onclick="fadeOutFadeIn('orange')">orange</button>
<button onclick="fadeOutFadeIn('red')">red</button>
<button onclick="fadeOutFadeIn('yellow')">yellow</button>
<button onclick="fadeOutFadeIn('pink')">pink</button>

Answer №1

In order to streamline your code and make it easier to maintain, I recommend using a single event listener instead of multiple ones. Utilizing classes over style tags is also advisable as it simplifies maintenance and facilitates transitions like css transitions. In this case, the items fade in and out smoothly.

Furthermore, I chose to implement setTimeout instead of a sleep function. According to a detailed explanation on Stack Overflow, using loops like while() can block code execution and cause performance issues. By using setTimeout or setInterval, you ensure asynchronous behavior and timely triggers for your functions.

window.addEventListener('DOMContentLoaded', () => {

  // one click-event listener to rule them all
  document.addEventListener('click', e => {

    // testing to make sure the item clicked is a button and is in the 
    // <div class='color-b'> element
    if (e.target.tagName === 'BUTTON' && e.target.closest('.color-b')) {
      let ev = e.target.innerText.trim() // get the id directly from the button text
      document.getElementById(ev).classList.add('dim');
      setTimeout(() => document.getElementById(ev).classList.remove('dim'), 1500);
    }
  })
})
img {
  transition: opacity 1s;
  width: 58px;
}

button {
  width: 58px;
}

.dim {
  opacity: 0.16;
}
<div id="epicenter">
  <img src="https://via.placeholder.com/65/000" alt="Schwarz" id="black">
  <img src="https://via.placeholder.com/65/00f" alt="Blau" id="blue">
  <img src="https://via.placeholder.com/65/0f0" alt="Grün" id="green">
  <img src="https://via.placeholder.com/65/ddd" alt="Grau" id="grey">
  <img src="https://via.placeholder.com/65/a0d" alt="Lila" id="lila">
  <img src="https://via.placeholder.com/65/e73" alt="Orange" id="orange">
  <img src="https://via.placeholder.com/65/f00" alt="Rot" id="red">
  <img src="https://via.placeholder.com/65/ff0" alt="Gelb" id="yellow">
  <img src="https://via.placeholder.com/65/fcc" alt="Rosa" id="rosa">
</div>
<div class='color-b'>
  <button>black</button>
  <button>blue</button>
  <button>green</button>
  <button>grey</button>
  <button>lila</button>
  <button>orange</button>
  <button>red</button>
  <button>yellow</button>
  <button>rosa</button>
</div>

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

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

Ways to format the direct descendant of a multi-level list?

Check out my nested ul list: <ul> <li> <a href="/"></a> </li> <li> <a href="/"> </a> &l ...

Concealing rows with empty cells in column E

As someone who is fairly new to incorporating scripts in Google Sheets, I stumbled upon this straightforward and beneficial code snippet online. My objective is to conceal rows within a specified range (rows 10 - 34) where there are blank cells in column E ...

allowing absolutely positioned region to expand

For further information, please visit this page: test page In the process of designing a website, I have implemented a sidebar featuring an accordion style vertical navigation bar. The sidebar is set to be absolutely positioned in relation to its containi ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

How does the call method on array.prototype.includes work with arguments x and y?

Curious about the functionality of array.prototype.includes.call(x, y);. Discovered that includes() confirms if an array has the specified value and provides a true or false result. Learned that call() invokes this alongside any optional arguments. The ...

Can we trust the security of this form?

Is the form secure when sending emails? Any security issues with SQL involvement? HTML: <form id="form4" action="send_mic.php" name="form4" method="post" > <textarea name="message4" cols="4" rows="4" id="message4" ></textarea ...

A reliable approach for dynamically altering SVG graphics

It seems like IE10 does not support CSS transformations for SVGs, only attribute transformations. Here is an example: <svg><rect id="myrect" width="200" height="200"></rect></svg> setTimeout(function() { var r = document.getE ...

relocate the image with an identical filename stored in the variable

Having trouble moving an image to a new position when clicking on its small thumbnail. I've attempted using jquery's find() function but it doesn't seem to be working... $('#slide1_controls img').click(function (event){ var sr ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

JavaScript functions may become unresponsive following ajax loading with tables

I have a table that is automatically generated by a database using PHP with four rows. The last row (4) has a button that triggers the function below, and this is repeated for every line. After clicking the button, the script sends a request to update the ...

Obtaining outcomes from all redux-saga operations, regardless of any potential failures

I am currently facing a situation where I have to execute multiple api calls simultaneously. The current code utilizes redux-saga's all method for this purpose: try { const results = yield all( someIds.map(id => call(axios.delete, ...

Enhancing an identity function with type hinting

I am looking to define a specification for a function that returns its input argument, regardless of its type. The crucial aspect here is to mirror the interface of the argument in the return value. For instance, when I type z. on line 6 as shown in the i ...

Modifying the design of a website in real-time using the EXPRESS.js and NODE.js frameworks

I successfully set up a simple website using node.js and express.js by following this helpful tutorial. My express implementation is structured like this with a jade file for the web interface. // app.js var express = require('express'), r ...

What is the process for obtaining a custom slot in a v-data-iterator?

How can I customize the slot in v-data-iterator to change the color and content of certain sections? Desired Customization: https://i.sstatic.net/bqdfL.jpg This is what I have tried so far: <!-- Custom slot for Calories --> ...

best way to sort through an array using jquery in javascript

Is there a way to filter a jQuery array like in SQL server with "Like % %"? var array=[ {"job_category":"hello sir","job_location":"hello dear"}, {"job_category":"dear kumar ","job_location":"sir"}, {"job_category":"testts ssss ss","job_location":"hello t ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...