What is the technique to enable this div to be clickable?

I am trying to make each "card" of a WordPress plugin clickable on my website. I have inserted a Pure JS element with the following code:

document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');}

Unfortunately, it is not working as expected. Can someone please help me figure out what I am doing wrong? Any assistance would be greatly appreciated. Thank you!

Answer №1

To add a click event listener to every card:

// Select all elements with the .fc_card-container class and store them in a variable
// Using .getElementsByClassName returns an array-like object containing all selected elements
var cards = document.getElementsByClassName('fc_card-container');

// Convert the NodeList of cards into an array using [].slice.apply(cards)
// Use .forEach to iterate through the array of cards

[].slice.apply(cards).forEach(function(card, index){ 

    // Each element in the array represents a card
    // Add an event listener for each card using .addEventListener(EVENT, callback)

    card.addEventListener("click", function(e){ 
        alert(); 
        console.log(cards[index]); // Index indicates the precise array position (index) of the clicked card
        console.log(e.target); // e.target provides access to the clicked element
    }); 

});

Answer №2

document.querySelectorAll gives you an array of elements that match your specified selector. In this scenario, it would return an array of elements with the class name fc_card-container. To proceed, you can loop through these elements and attach an event listener to each one individually or target a specific element using its index (starting from 0).

Attaching Click Event to All Elements

var cards = document.querySelectorAll('.fc_card-container');
for(var i = 0; i < cards.length; i++){ //loop through each card
   cards[i].onclick = function() {alert('Success!');};
};

Attaching Click Event to a Single Element (e.g., 3rd element)

var cards = document.querySelectorAll('.fc_card-container');
cards[2].onclick = function() {alert('Success!');}; //0,1,2

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

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...

Utilizing the map() method for iterating through a nested property within a React component

Currently, my React setup involves rendering a prop named area which has the following structure: [{ "id": 1, "name": "Europe", "Countries": [{ "id": 1, "name": "Iceland", "Cities": [{ "id": 1, " ...

Customizing the initial search parameters in Vue InstantSearch: A step-by-step guide

I am utilizing the Vue components from Algolia to perform a search on my index. The search functionality is working correctly, but I am curious about setting the initial values for the refinement list upon page load. This is how I have set up the search: ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Can someone please clarify how the nth-of-type selector functions?

I can't understand why the nth-of-type selector needs to be set to 2 instead of 1 for the first sibling of this type in the code. To see the code in action, check out this jsfiddle: https://jsfiddle.net/xj5hvn16/ If anyone could kindly provide an ex ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Revalidating doesn't seem to work as expected in Next JS

Reviewing my code on the development server function Home(props) { console.log("Hello") return ( <ul> {props.user.map((user) => ( <li key={user.id}>{user.email}</li> ))} </ul> ) } expo ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...

Changing variables within anonymous functions in javascript can be done by using the parameters passed into

Hello everyone, I'm currently working on a new JavaScript project and I've encountered an issue. I need to figure out how to change variables in anonymous functions. Can anyone help me with this? updateName : function(){ var firstNa ...

Deciding on pixel values, percentages, and sizing elements within CSS styles

For all you web development experts out there, I have a question regarding CSS styles. I often see precise pixel or percentage measurements used for properties like "padding" and "height." Experienced developers seem to effortlessly position their content ...

Error: Jasmine cannot access a property of undefined value

Just getting started with js and jasmine Attempting to create a jasmine test case for my method. Encountering an error: TypeError: Cannot read property '0' of undefined. Tried different ways of passing arrays into my method sports but still facin ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

The video on mobile is not loading properly, as the play button appears crossed out

There seems to be an issue with GIFs not loading on mobile devices, even though they are implemented as mobile-ready. <video src="/wp-content/uploads/2017/09/5.mp4" preload="metadata" autoplay="autoplay" loop="loop" muted="muted" controls="controls" ...

Using AngularJS to compare values against user input to determine if they are greater or lesser

When a user inputs data into an input field, it must fall within the range of values retrieved from the database. The value entered by the user should meet either the minimum, maximum, or default value obtained from the database. For instance, if the minim ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Ways to implement CSS styling for a particular HTML element

HTML: <div class="tagline">Web Portal Name</div><br /> <div id="logged_in_user_dtls" style="color:#FFF; margin-top:15px; font:bold; width:100%; position:relative; margin-left:800px;float:left;"&g ...

Can a vertical line be sketched next to a horizontal line?

Let's keep it short and sweet. Here's what I'm attempting to achieve: Currently, this is what I have: Below is the code snippet: #ligne_horizontale_experience { margin-left: 50px; width:170px; height:400px; border ...