0

I wanto to make each "card" of this wordpress plugin clickable (http://www.davidbo.dreamhosters.com/?page_id=11)

So I added a Pure JS element with the following code:

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

and it is not working so I wonder how wrong this is.

Thanks !

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Ariel
  • 549
  • 1
  • 5
  • 13

2 Answers2

4

If you want to apply a click event handler for all the cards:

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

// Use [].slice.apply(cards) to convert the cards NodeList into an array
// Iterate over the cards array with a .forEach

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

    // Each array element corresponds to a card element
    // Use the .addEventListener( EVENT, callback ) to attach an event handler for each card element

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

});
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
0

document.getElementsByClassName returns an array of matched elements. In your case, an array of elements with the class name of fc_card-container. Your next step would be to iterate over the elements and assign an event listener to each or select a specific one using an index (starting with 0).

Assign a click to all

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

Assign a click to a single card (eg: 3rd card)

var cards = document.getElementsByClassName('fc_card-container');
cards[2].onclick = function() {alert('It works!');}; //0,1,2
Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40
  • I've added code value of 'i' variable in alert('It works!' + i) but 'i' variable always get count of div classes found. How can I get exactly the box number, which it has clicked – Akash KC Dec 28 '15 at 04:51
  • That's because that's the final number that i becomes at the end of the loop. – Donnie D'Amato Dec 28 '15 at 05:04
  • This might help: http://stackoverflow.com/questions/8801787/get-index-of-clicked-element-using-pure-javascript – Donnie D'Amato Dec 28 '15 at 05:05