Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together.

I suspect there may be an error in my JavaScript code.

In the original code, I used images in front and an unordered list in the back, but here I have simplified it to just "Front" and "Back".

$(".flip").click(function() {
  $(".card").toggleClass("flipped");
});
.card-container {
  display: flex;
}
.card {
  width: 300px;
  height: 6rem;
  margin: 30px;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.card figure {
  margin: 0;
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.card figure figcaption {
  padding: 0 1rem;
  backface-visibility: hidden;
  border: 1px solid gray;
}

.card button.flip {
  position: absolute;
  right: 1rem;
  margin: 0;
}

.card button.flip {
  top: 1rem;
}

.card .back {
  transform: rotateY( 180deg);
}

.card.flipped {
  transform: rotateY( 180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-container">
  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 1</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 1</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>

  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 2</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 2</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>
</div>

Could someone point out what could be going wrong here?

Answer №1

There is a more efficient way to handle the flipping of elements with the class .card. Instead of toggling all elements, you can toggle only the one that contains the button by using the .closest() method, which moves upwards in the DOM tree until it finds the specified class.

$(this).closest(".card").toggleClass("flipped");

$(".flip").click(function() {
  $(this).closest(".card").toggleClass("flipped");
});
.card-container {
  display: flex;
}
.card {
  width: 300px;
  height: 6rem;
  margin: 30px;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.card figure {
  margin: 0;
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.card figure figcaption {
  padding: 0 1rem;
  backface-visibility: hidden;
  border: 1px solid gray;
}

.card button.flip {
  position: absolute;
  right: 1rem;
  margin: 0;
}

.card button.flip {
  top: 1rem;
}

.card .back {
  transform: rotateY(180deg);
}

.card.flipped {
  transform: rotateY(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-container">
  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 1</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 1</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>

  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 2</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 2</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>
</div>

Answer №2

$(".flip").click(function() {
  $(this).closest(".card").toggleClass("flipped");
});
.card-container {
  display: flex;
}
.card {
  width: 300px;
  height: 6rem;
  margin: 30px;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.card figure {
  margin: 0;
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.card figure figcaption {
  padding: 0 1rem;
  backface-visibility: hidden;
  border: 1px solid gray;
}

.card button.flip {
  position: absolute;
  right: 1rem;
  margin: 0;
}

.card button.flip {
  top: 1rem;
}

.card .back {
  transform: rotateY( 180deg);
}

.card.flipped {
  transform: rotateY( 180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-container">
  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 1</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 1</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>

  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 2</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 2</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>
</div>

Answer №3

To avoid flipping all the cards simultaneously, it is important to use unique IDs to distinguish between individual cards instead of simply relying on the .card class. By uniquely identifying each card, you can specify which cards should be flipped when the action is triggered.

Answer №4

const cardElement = document.querySelectorAll('.card');
for(let i = 0; i < cardElement.length; i++) {
  cardElement[i].addEventListener('click',function(){
    this.classList.add('flipped')
  })
}
.card-container {
  display: flex;
}
.card {
  width: 300px;
  height: 6rem;
  margin: 30px;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.card figure {
  margin: 0;
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.card figure figcaption {
  padding: 0 1rem;
  backface-visibility: hidden;
  border: 1px solid gray;
}

.card button.flip {
  position: absolute;
  right: 1rem;
  margin: 0;
}

.card button.flip {
  top: 1rem;
}

.card .back {
  transform: rotateY( 180deg);
}

.card.flipped {
  transform: rotateY( 180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-container">
  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 1</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 1</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>

  <div class="card">
    <figure class="front">
      <figcaption>
        <h2>FRONT 2</h2>
        <button class="flip">+</button>
      </figcaption>
    </figure>
    <figure class="back">
      <figcaption>
        <h2>BACK 2</h2>
        <button class="flip">-</button>
      </figcaption>
    </figure>
  </div>
</div>

Perhaps a good approach would be to retrieve all elements with the class card first and then iterate over them. Below is an example in plain javascript:

const cardElement = document.querySelectorAll('.card');

Then iterate over the elements using a loop:

for(let i = 0; i < cardElement.length; i++) {
  cardElement[i].addEventListener('click',function(){
    this.classList.add('flipped')
  })
}

You can experiment with toggling the flipped class to achieve desired effects.

Answer №5

In response to your previous inquiry about learning jQuery and/or React, I initially tried to address it in a comment but found myself running out of space. Thus, I opted to transform my lengthy comment into a separate answer.

There were originally two main reasons for utilizing jQuery, both of which are now outdated.

The first reason pertained to browser compatibility, particularly with IE. In the past, we had to cater to two types of browsers: IE and all others. IE posed unique challenges that necessitated separate handling. However, with the demise of IE by Microsoft, this reason is no longer relevant.

Fun fact: The disparity in IE was not due to Microsoft's programming capabilities, but rather an attempt by the company to compete in a realm (the Internet) where free software products dominated. By introducing a browser (IE) bundled with Windows, Microsoft sought to ensure compatibility with their webserver (IIS). This strategy ensured optimal performance only with IIS, compelling entities like banks and multinationals to invest in Microsoft solutions to avoid website display issues on the most widely used browser.

The second reason for adopting jQuery was to simplify javascript operations with functions like $.each(), $.ajax(), and .on(), which were more user-friendly than native javascript. However, advancements in "modern javascript" like es6 have bridged this gap, rendering jQuery less essential. Therefore, mastering javascript should be a primary focus alongside jQuery knowledge.

Despite its continued prevalence on approximately 70% of websites and integration with libraries like Bootstrap, understanding native javascript takes precedence. While jQuery remains useful, learning modern javascript is vital. Check out these resources demonstrating the transition from jQuery to newer javascript methodologies.

Streamlined element selection in pure JS

Pure JS alternative to jQuery remove()


Regarding learning React:

The decision to delve into React hinges on your objectives. For career prospects, knowledge of React, Angular, or Vue.js is beneficial. However, for those focused on creating innovative web functionality, proficiency in javascript, graphing libraries (D3.js, Dash-Plotly), Python for scientific/mathematical contexts, and PHP for robust backend development is crucial. Remember, even Facebook transitioned to their proprietary system (React) from PHP and MySQL relatively recently.

For additional insights on learning React, refer to this informative post:

React site displaying blank page on GitHub Pages

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

What are the steps to displaying Jade in an Electron application?

With Express, you can easily establish the view engine as Jade by using the following code snippet: app.set('view engine', 'jade'); This enables Express to parse and deliver compiled HTML from Jade files directly. But how can this be ...

Creating a personalized mouse cursor using HTML

I am trying to set an image as my cursor inside a div container but I want it to disappear and revert back to a normal pointer cursor when the mouse hovers over any link within that div. Here is my code snippet: var $box = $(".box"); var $myCursor = $ ...

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

What is the best way to display converted value in Angular 8?

In my current project, I am utilizing .NET Core 2.2 for the backend and Angular 8 for the frontend. The scenario involves having integer values on the backend within a specified range. For example: [Required] [Range(1073741824, 1099511627776)] // ...

Implementing function invocation upon scroll bar click

I have a Div element with a scroll bar. When a user clicks the scroll bar, I want to call a function based on that click event. How can I achieve this? On the client side, I am using jQuery and on the server side, I am using PHP. I am familiar with makin ...

Revamping the design of a menu bar in WordPress

I designed a navigation bar and now I'm looking to customize the CSS for it in WordPress. Specifically, I want to be able to reference the nav bars by name from PHP to CSS. It seems like there are just two dots representing variables. Here is the co ...

Notification with jQuery

I am looking to display an alert message when val = -1. However, the issue I am facing is that this message always appears at the bottom of the page regardless of the value of val. if ($val == -1) echo ' <script> $( ...

What is the best way to include an Interval in a button element?

I am currently working on developing an application that will automatically take a picture every minute using the camera. I want to implement a button tag with an interval so that when the application is running, it will capture an image every minute. i ...

localization within vue component

if (self.form.pickupTime == '') { self.formError.pickupTime = 'Please enter a pickup time that is ready for collection.'; status = false; return status; } else { self.formError.pickupTime = ''; } I am struggling ...

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

I am experiencing issues with staying logged in while using Passport and sessions. The function "isAuthenticated()" from Passport continuously returns false, causing me to not remain logged in

I have been working on implementing authentication with Angular, Passport, and sessions. I can successfully create a new user and log in, but I am facing an issue: Problem Every time I check if the user is authenticated using Passport's isAuthentica ...

How to position a static element using CSS

I'm trying to align an image in the center of the screen, but I've run into some trouble. Typically, this is easy by setting the width of a div and using margin: auto;. However, I also need the div to have the position: fixed; property, which see ...

Arrangement of HTML divs and styling classes

I have been experimenting with divs and classes in order to achieve proper alignment of text on my website. Currently, I am working with 2 classes that I would like to display side by side to create 2 columns. However, the right column containing the text ...

The Facebook JavaScript API function FB.api() is limited to posting messages and does not support media attachments

I am attempting to share a message with an mp3 attachment on the active user's wall. It works perfectly fine within Facebook's Test Console, but when I try it from my mobile app, only the message gets posted. Can anyone help me figure out what I ...

Can we expect every bullet point to be consistently indented at precisely 1.8em?

Recently, I created a dropdown menu using only CSS. The challenge was to have a horizontal bar of items that can each expand into a vertical menu. However, I wanted the expanded menus to display bulleted lists instead of tertiary menus. By nesting three ul ...

Guide on generating a dynamic table by looping through an array and placing values inside <tr> tags, then saving it in a variable

I am working with an array object and need to dynamically create a table where each tablerow (tr) pulls values from the array object. After creating the table, I want to store it in a variable so that I can pass it to a rest call, triggering an email with ...

Issue: Unable to locate file 'socket.io-client/dist/socket.io.min.js'

Attempting to set up the Spika backend (node application), I ran into an issue while trying to start the server in standalone mode with the command: $ node src/server/main.js The error that popped up was: Error: Cannot find module 'socket.io-clien ...

Determine the height of the input group when a span, input, and button are included

I have been attempting to create a 3 control input-group using Bootstrap 3.3.7, but I am encountering an issue where the height of the first addon does not match the height of the input field or button that follow. <div class="input-group"> < ...

What are the steps to send $http requests from AngularJS to a local server in an app?

Situation at Hand My goal is to perform an $http post request from Angular using the function below, defined in my controller: $scope.sendUserData = function(){ var userData = JSON.stringify({ 'firstName': $scope.firstName, ...

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...