Dustin
Dustin

Reputation: 397

Flipping a Card triggered by Button

I want to have two cards defined, and flip them to toggle the view. I want an edit and save button to ultimately trigger the flip. But I'm stuck on triggering the button (still learning)

This example project here flips the card when the card is clicked but not the button itself. If I remove the action from the card and assign a onclick="flipCard()" function... I'm not sure what to define in that function.

This JS code I found in some examples online

$('.flip-card').on('click', 
  function(){
  //console.log($(this));
    $(this).toggleClass('flipped')
  }
)

I want to attach this functionality but on an onclick method.

Can you point me in the right direction?

Upvotes: 1

Views: 2054

Answers (3)

Md. Abu Sayed
Md. Abu Sayed

Reputation: 2486

You can solve it multiple ways like as:

Example-1.

Html

<div class="flip-card mb-3 " onclick="flipCard(this)">

Javascript

function flipCard(el) {
   $(el).toggleClass('flipped')
}

Example-2. just write jquery code here

$(document).on('click', '.flip-card',function(){
   $(this).toggleClass('flipped')
});

===Thanks===

Upvotes: 1

Djave
Djave

Reputation: 9349

With jQuery you target things $(...), and then inside the callback function optionally refer to them with $(this).

So in your example, you target the flip card:

$('.flip-card').on('click', function(){

Then flip it:

$(this).toggleClass('flipped')

You can easily attach the trigger to the button, and the class update to the card. Remove the onclick bit, and just use jQuery.

// Target the button click...
$('button').click(function(e){
  // toggle the flip class
  $('.flip-card').toggleClass('flipped')
});

Or without jQuery it would look something like this, there are a couple more complexities with targeting all the buttons and their counterpart cards, but just as a pointer to get you started:

document.querySelector("button").addEventListener("click", function(){
  document.querySelector('.flip-card').classList.toggle('flipped');
});

Upvotes: 2

bgazsi
bgazsi

Reputation: 141

The listener has the this keyword in it, but it is different on every element the handler is invoked on. You should try something like this:

$('.flip-toggle').on('click', 
  function(){
    $(.flip-card).toggleClass('flipped')
  }
)

Upvotes: 0

Related Questions