Reputation: 547
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 !
Upvotes: 0
Views: 260
Reputation: 5412
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
});
});
Upvotes: 4
Reputation: 3940
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).
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!');};
};
var cards = document.getElementsByClassName('fc_card-container');
cards[2].onclick = function() {alert('It works!');}; //0,1,2
Upvotes: 0