Struggling to get the if statement to work with hasClass() implementation

Currently, I am creating a memory game where the .flip class is added to a card when it is flipped. To track if two identical cards have been chosen, I am using the hasClass() method.

The issue is that the jQuery for hasClass() doesn't seem to be functioning correctly. The console log isn't displaying anything. Here's the snippet of my jQuery code:

$(document).ready(function(){

        var counter = 0;

        if(counter == 0){
            console.log(counter);
            // setting up click/tap panels
            $('.click').toggle(function(){
                counter = 1;
                console.log(counter);
                $(this).addClass('flip');
            },function(){
                /*$(this).removeClass('flip');*/
            });
        }

        if($("#heart-01").hasClass("flip") && $("#heart-02").hasClass("flip")){
            console.log("yo");
        }

    });

Below is the HTML structure:

<div id="heart-01" class="panel click heart">

    <div class="front"></div>

    <div class="back"></div>

</div>

<div id="heart-02" class="panel click heart">

    <div class="front"></div>

    <div class="back"></div>

</div>

Here's the CSS style sheet attached:

.panel {
        float: left;
        width: 150px;
        height: 150px;
        margin: 20px;
        position: relative;
        -webkit-perspective: 600px;
        -moz-perspective: 600px;
    }

/* -- Y axis rotation and general style for heart card -- */
// CSS styles go here...

.click .front {
        cursor: pointer;
        -webkit-transform: rotateX(0deg);
        -moz-transform: rotateX(0deg);
    }
    // More CSS styling...

Answer №1

In order to properly test the classes within an event handler, make sure to place your if clause inside it. Currently, it is part of the document.ready handler causing the test to only occur once when the page is initially loaded.

Additionally, note that the two function version of .toggle() has become deprecated.

For the required functionality, consider using the following approach:

$(document).ready(function(){

    $('.click').on('click', function() {
        $(this).toggleClass('flip');
        if ($('.flip').length === 2) {
            console.log('yo');
        }
    });

});

View example at http://jsfiddle.net/alnitak/Xtw58/

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

Guide to implementing sliding effects with Jquery

I recently dived into the world of JavaScript and jQuery. I crafted a piece of JavaScript code for client-side validation. document.getElementById(spnError).style.display = 'block'; Currently, I am displaying a span element if any validation er ...

External style sheet link is not operational

Inside base.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Base</title> <style> body { background: blue; } </style> </head> <body> &l ...

I customized the navbar in Bootstrap by centering it with custom CSS, but whenever I click on it, it suddenly shifts to one side. I'm puzzled as to why this is happening and

I attempted to center my navbar-toggler element, but was only successful in centering the navbar-contend using Bootstrap. I then took it a step further by trying to center the navbar-toggler icon with custom CSS, however, it now shifts to the left when cli ...

Utilize the jsTimezoneDetect script to showcase a three-letter time zone code

I'm currently utilizing the jsTimezoneDetect script to identify the user's current timezone. The code below shows the result as America/Chicago. Is there a way to display CDT/CST instead (based on today's date)? var timezone = jstz.determin ...

Flask returns a BadRequestKeyError when a post request is made to the server with an HTML

I need to pass the text value of a span element to Flask using an Ajax post request like this: <span id="myspan">text</span> Here is the function for uploading columns: function upload_columns (){ let spantext = { mainfi ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...

An alternative option for the location parameter in the post

$.post("location_example.php",{data:data},function(){ //performing some action }); I attempted to specify the full location path as "localhost:8888/myweb/data/index.php", but it does not seem to be posting anything. It appears that the parameter cannot ...

Introduce a loading screen to display as users navigate between HTML pages

I am looking to incorporate a mp4 animation as a loading screen between two html pages. The video lasts approximately 5 seconds, so I would like the loading page to display for the same amount of time. Is there a way to achieve this? Additionally, is it p ...

Optimizing WordPress with server-side AJAX caching

I am looking for a way to store AJAX responses on the server side rather than constantly retrieving data from the database every time a client makes a request. function post_filter($filter_action,$filter_values) { var ajaxurl = SiteInfo.home_url+&apos ...

Using JQuery and ColdFusion components to verify the presence of a record in the database during the login

I've been working on creating a similar login/forgot password pop-up like the one on download.cnet.com. My code is functioning properly, but I've encountered an issue - it doesn't work when pressing enter. The form gets submitted, but the aj ...

When aligning divs at the center, they may not all be perfectly in a straight

My goal is to align 4 div boxes in a vertical line using the translate method typically used for centering objects on a webpage. Here is the code snippet I have utilized: link .body-component { position: relative; margin: 10px; color: #000; disp ...

Add rows to the table dynamically and then execute the script

My table dynamically creates rows when a button is clicked, and there is an input box with an auto suggest script. The auto complete works fine on the default first box, but not on the dynamically added row. How can I make the auto complete script work o ...

What is preventing me from receiving the value from the Ajax call?

I have developed an Ajax function that looks like this: function searchPlanAjax(url){ jQuery('#loader').css('display','block'); var plan = jQuery('.rad').val(); var site = url+"fbilling_det ...

Stop the slider when a video pops up

Years ago, I had a slider created for me that supports both images and video with a timer. However, the issue I'm facing is that when the timer runs every 10 seconds, the video gets cut off if it's not finished playing. Below is the json file st ...

How to Overlay a Semi-Transparent Object on a Background Video using CSS and HTML

Hey there, I'm encountering a puzzling issue with my website. I have a background video set up, and I wanted to overlay a floating textbox on top of it. However, no matter what I do, the background color and borders of the textbox seem to be hiding be ...

Maintaining characteristics while utilizing jQuery's grep functionality

Extracting unique objects from an object array while manipulating it poses a challenge. Although inArray and grep are options, both have their limitations. InArray struggles with testing nested properties, while grep lacks the capability to modify objects ...

How can you ensure data is saved during the process of moving datarows between two gridviews using drag and drop functionality?

I am currently working on implementing drag and drop functionality to move data between two gridviews. The goal is to save the data in a database on Azure once it has been moved from one gridview to another. However, I am facing an issue where the data is ...

Is it possible to dynamically convert percentages to pixels in real-time?

I am working on a project with a fluid percentage-based horizontal grid and I want to have the same vertical margins as my horizontal ones. This is the code I have: .block_12_24{ display:inline-block; vertical-align:top; width:48%; margin-right:2%; margi ...

Rearranging Information for Optimal Mobile Viewing

I am in the process of designing an HTML email template, and I am working on ensuring its compatibility with mobile devices. Currently, I have arranged an image, followed by text and a button, but my goal is to switch the order for mobile displays so that ...

Creating a popup window using HTML

I am attempting to create a pop-up window using HTML, but I'm struggling to get it to appear in the desired way. My goal is this: to have a pop-up show up when the profile image is clicked on. Here's the HTML <span class="profile"><im ...