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

"Place text at the center of a div that is rotated

I'm facing the challenge of centering a heading both vertically and horizontally within a div that has been rotated 45 degrees (transform:rotate(45deg);). Due to this rotation, I have attempted to counteract it by rotating the heading in the opposite ...

Steps to sending an email to an administrator using PHP and jQuery

I am looking for a way to send a notification email to my site admin whenever a user submits a request via a form. Currently, I have the following code that is supposed to link to a PHP file on my server to handle the email sending: $("#modelform").submit ...

Injecting a controller into an AngularJS module within an anonymous function

As a newcomer to the world of javascript and just beginning to work with angular.js, I have a question. I'm wondering if there is a method for injecting a controller into a module that is declared within an anonymous function. This is how my code cu ...

Exploring Browser History using Cascading Style Sheets

Currently, I am in need of researching a topic for my University project. Unfortunately, the internet has not provided me with any information on this specific subject. The task at hand is as follows: "How and under what circumstances can one uncover ...

Utilizing the position relative property with Firefox browser

Similar Question: Is Firefox compatible with position: relative on table elements? Check out this example: a full-width menu formatted as a table with ul dropdown menus. Everything works as expected in IE and Opera, but in Firefox the dropdown uls ex ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

jQuery checkbox toggles multiple divs instead of targeting specific ones

I have set up my page to display divs containing posts using a specific format. The divs are structured as follows (replacing # with the postID from my database): <div id="post_#> <div id="post_#_inside"> <div id="like_#"> ...

Parse multiple JSON files, manipulate their contents, and store the updated data

I'm currently working on implementing this functionality using Gulp. Locate and access all files with the extension .json within a designated directory, including any subdirectories. Perform modifications to the files in some manner, such as adding ...

"Troubleshooting: Why Won't insertAfter Function Work with

I have a p Element that I want to wrap inside a span tag. Then, I need to insert it after another p tag with the id output. Despite my attempts, the insertAfter function is not working as expected. $mytext = $("p#test").html(); $myspan = "<span styl ...

How can AJAX be utilized to show search results dynamically?

At the moment, I have a PHP page that pulls a list of results from my SQL database and displays the ID and names. There is a search bar at the top where you can search for keywords in the "name" field, and when you click on search, it takes you to a new p ...

What is the method to extract a value from the $emit payload using Vue.js?

I have a situation where I am sending an event with different values from my ConversationList component (child) to the ConversationModel component (parent). Conversation List getConversation(conversation_id, receiver_id, username, avatar){ this.$emit(& ...

The checkbox generated from the JSON is failing to display the alert when it is clicked

I have been trying to pass checkbox input from JSON into HTML. When I click on the checkbox, an alert should pop up, but it's not working. Here is my code: $aroundCheck='<div id="content">'; foreach ($checkLocation as $checkLocation) ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Convert a JSON array with a single element into a valid JavaScript object

Within my programming scripts, I frequently utilize PHP arrays with numeric keys. However, these keys are not necessarily sequential from 0 to n; they can be randomly chosen. Specifically, I am working on a script that organizes scheduled events at specifi ...

The iFrame is set to a standard width of 300 pixels, with no specific styling to dictate the size

My current challenge involves utilizing the iframe-resizer package to adjust the size of an iframe dynamically based on its content. However, even before attempting any dynamic resizing, I encounter a fundamental issue with the basic iframe: it stubbornly ...

Having difficulty modifying styles within the React Material-UI app bar component

I created a unique component and tried to implement it in AppBar, but the styles are not being overridden. I utilized the makeStyles hook which works perfectly fine outside of the AppBar, however, within the AppBar and ToolBar, I am encountering difficulti ...

Do not directly change a prop - VueJS Datatable

Just starting out on Vue JS and encountered an issue while trying to create a Data Table by passing parent props to child components. An Error Occurred: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent ...

Changing Text in React Native is Customizable

As a newcomer to react native, I find myself in need of some guidance. I am currently working on implementing a TextInput feature where users can update the text value as they please. For instance, if a user initially creates a folder named "Bar" but later ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

Every time I use Axios with NextJS, I keep getting a frustrating 405 method not allowed

I am facing a challenging issue with this... Currently, I am using NextJS for the frontend and making a request to <frontend-domain>/api/auth/register from here. const changePassword = async (currentPassword, password) => { await axios.post(& ...