Ariel
Ariel

Reputation: 547

How to make this div clickable?

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

Answers (2)

Kostas Minaidis
Kostas Minaidis

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

Donnie D'Amato
Donnie D'Amato

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).

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

Upvotes: 0

Related Questions