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

HTML Button without Connection to Javascript

When attempting an HTML integration with GAS, the code provided seems to be generating a blank form upon clicking "Add" instead of functioning as expected: //GLOBALS let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = ss.getLa ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

Combining rows and columns in Flexbox design

https://i.stack.imgur.com/tDLii.png I'm able to easily create this layout using the float property, but I'm having some difficulties achieving the same with flexbox. CSS: .a { background: red; float: left; width: 30%; ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Extract data from JSON in Google Sheets

UPDATE: entry.content.$t is actually not the correct field to access individual cells. The proper method is using entry.gsx$[cell column header]. Thank you for pointing out this mistake and assisting in finding a solution. Initial inquiry: I am currently ...

Insert a division into the table following every row

I'm working with a table that can be found here: https://codepen.io/anon/pen/bjvwOx Whenever I click on a row (for example, the 1st row 'NODE ID 1'), I want the div with the id #divTemplate to appear below that particular row, just like it d ...

Leveraging AJAX within a RESTful API in a Node.js environment to retrieve a JSON file and dynamically parse its contents according to the specific button selected on the front-end interface

Can anyone help me with understanding the communication process between server.js (Node.js) and the front-end JavaScript file? I am trying to implement AJAX as a RESTful API in the server to retrieve a JSON file, parse it based on specific button clicks in ...

Enable the bottom footer to expand along with the content to support a dynamically growing page

I followed a tutorial on keeping footers at the bottom of a webpage (http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page) to create a site with a fixed footer. However, I encountered an issue when there is more content than can fit ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

Peeling back the layers of a particular element

This is my code snippet: <pre id='code'> <ol> <li class='L1'><span>hello</span></li> <li class='L2'><span>Hi</span></li> <li class='L3&apos ...

Struggling with a TypeError in React/Next-js: Why is it saying "Cannot read properties of undefined" for 'id' when the object is clearly filled with data?

Encountering an issue with a checkbox list snippet in Next-js and React after moving it to the sandbox. Each time I click on a checkbox, I receive the error message: TypeError: Cannot read properties of undefined (reading 'id') This error is co ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

What is the best way to incorporate a <li> view cap within a div element using JavaScript?

Currently, I am attempting to implement a dynamic <li> view limit within the content of a div. My goal is to display only 3 <li> elements each time the div content is scrolled. Although not confirmed, I believe this example may be helpful: ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Unable to vertically scroll on a position fixed element

I recently created a unique VueJS component that enables vertical scrolling. Within this component, there are two elements each with a height of 100vh. At the bottom of the component is a fixed position div. Interestingly, when I try to scroll down using m ...

What are the steps for implementing pytesseract on a node.js server?

While working on my node.js server, I encountered an issue when using child-process to send an image to a python script. Although I can successfully read the image in the python script, I encounter an error when attempting to convert it to text using pytes ...

Numerous sections of content

Struggling to align these two pieces of content side by side. While I've had success displaying content like this in the past, I'm hitting a roadblock this time around. Any assistance would be greatly appreciated. HTML <div class="block-one" ...

Place the emoji where the cursor is located

My query was already posted on stack overflow but unfortunately, I did not receive a response. The issue revolves around 2 links named "add emoji 1" and "add emoji 2". As mentioned earlier, my question can be accessed here: Insert smiley at cursor positio ...