Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly because I keep getting an error saying that it is not defined.

<div class="opaque">
<h3>Fade Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="opaque">
<h3>Fade Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="opaque">
<h3>Fade Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

 var o =1;
 var r = 0.1;
 var a;
 var counter;
 var e;


 function myFunction(e)
{
 e = this.style.opacity = o;
console.log(this.style.opacity);
counter = setInterval(fadeO(e),5000);



}

function execute()
{  


  a = document.getElementsByClassName('opaque');
  for( var i = 0; i< a.length; i++)
  {
    a[i].addEventListener('click',myFunction(e));
  }

}//end execute

function fadeO(e)
{
 this.a = document.getElementsByClassName('opaque');


if(e.style.opacity <=0)
{
 clearInterval(counter);
}
else{
 e.style.opacity = o ;
 console.log(e.style.opacity);
  o -=0.1;

}
}

window.onload = function()
{

execute();

} 

Answer №1

There are a couple of issues here, namely in the usage of addEventListener and setInterval(). Instead of passing function references, you are directly invoking the handlers.

var o = 1;
var r = 0.1;
var a;
var counter;
var e;


function myFunction(e) {
  this.style.opacity = 1;
  console.log(this.style.opacity);
  counter = setInterval(fadeO.bind(this), 100);//remember to pass a function reference to `interval()` without invoking it by adding (), in this modification, instead of passing the element reference as an argument we are passing it as the `this` reference using Function.bind()
}

function execute() {
  a = document.getElementsByClassName('opaque');
  for (var i = 0; i < a.length; i++) {
    a[i].addEventListener('click', myFunction);//ensure to pass the handler reference, avoiding invocation with `()`
  }

} //end execute

function fadeO() {
  if (this.style.opacity <= 0) {
    clearInterval(counter);
  } else {
    this.style.opacity = o;
    console.log(this.style.opacity);
    o -= 0.1;
  }
}

window.onload = function() {
  execute();
}
<div class="opaque">
  <h3>Fade Heading</h3>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
    quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="opaque">
  <h3>Fade Heading</h3>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
    quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="opaque">
  <h3>Fade Heading</h3>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
    quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.</p>
</div>

Note: This solution may require additional modifications to handle multiple clicks and similar functionalities

Answer №2

Can you explain the significance of variable e in the following code snippet?

for( var i = 0; i< a.length; i++)
  {
    a[i].addEventListener('click',myFunction(e));
  }

Consider the revised code below:

for( var i = 0; i< a.length; i++)
  {
    a[i].addEventListener('click',myFunction, false);
  }

Further insights can be found here. The context of this is determined by how your function is invoked. In this scenario, when called correctly, this should correspond to the value of your e. For more details, refer to this resource.

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

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

Creating a typewriter effect with Vue Js

Hey there, I'm having some trouble with the code below while working on my Vue project. It seems to be functioning correctly, but for some reason it's not working in my Vue environment. const text = document.getElementById("text"); const phrase ...

How can we integrate this icon/font plugin in CSS/JavaScript?

Check out the live demonstration on Jsfiddle http://jsfiddle.net/hc046u9u/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materializ ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...

The Ocelot API Gateway is a powerful tool for managing

I encountered an issue while working on my API gateway project. I initially installed the latest version of Ocelot (16.0.1), but it did not function correctly. The problem was resolved by reverting back to Ocelot version 15.0.6, while keeping my .NET Core ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...

Using Event Delegation in Practice

I am facing an issue with loading 2 <span> elements from separate ajax scripts onto a webpage upon selection from a dropdown box. Here is a snippet of my code: <span id='room_rate'>1,000</span> // content loaded by one ajax scri ...

Encountering a malfunction while executing an npm command specified in the package.json file

Currently, I am following a tutorial on Node, React, and Express on Udemy. In the tutorial, when I execute the command npm run data:import I encounter the following error: undefined npm ERR! code ELIFECYCLE npm ERR! errno 1 ...

Select options with disabled sorting feature

Is there a way to use CSS to sort disabled options in a select element? I would like all disabled options to appear at the bottom, with enabled options at the top. In the screenshot attached, you can see that enabled options are black and disabled options ...

Struggling with Vue's Router Transition fade in/out effect not functioning as expected?

Question: I've implemented Vue's Router and it switches between components without any issues. However, I added a <transition name="fade" mode="out=in"> around it but the fade effect is not working as expected. Desired ...

Guide on attaching an onclick function to a search bar

I found a search bar code on this website and I want to enhance it by adding a function that redirects users to a URL when they click on the search icon. Here is the existing code: <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> ...

Tips for making your inner content as wide as possible

I'm currently working on developing collapsible tables, where an outer and inner table are displayed for every row that is clicked. This is the code I have implemented: HTML: <table class="table outerTbl mb-0"> <thead> <t ...

The multiline feature of tooltip on mat-table cell is malfunctioning

I adjusted the mat-tooltip to be displayed as multiline using the following style in the global CSS: .mat-tooltip-class-here { white-space: pre-line !important; } Interestingly, this formatting works on span and button elements but not on mat cells. ...

Incorrect synchronization in the SVG arrow animation

How come the arrow doesn't start moving at the same time as the line? Is there a synchronization issue? I want the arrow to begin its journey simultaneously with the line. .container{ width:100%; padding:0px; background-color: black; } .squig ...

Incorporate a line break into a document using JavaScript

Is there a way to make all the items inside document.get on new lines without using paragraph elements? I have tried br/ and \n, but they do not work as expected. They either cause issues with JavaScript execution or fail to create new lines. <scr ...

What is preventing the successful insertion of a JSON array into a SQL database?

I am facing an issue with inserting a JSON array into an SQL database. I have an HTML table that stores its data in a JavaScript array, converts it to a JSON array, and then sends it to a PHP file. However, when trying to insert this JSON array into the da ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

Capturing keydown events exclusively in the topmost layer of the HTML document

Currently, I am developing a web application that includes an underlying HTML file with some JavaScript functionality that I cannot modify. In my code, I create a layer on top of this page using CSS with z-index: 1000;. However, I am facing an issue where ...

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...