Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to compare and determine if they match. Is this approach feasible and appropriate?

The main question I have is - how can I compare the classes of two elements?

$(function() {
  $("#answers div").draggable();
  $("#box div").droppable({
    drop: function(event, ui) {
      $(this)
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
    }
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>QUIZ</title>
  <link href='style.css' rel='stylesheet'>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>

<body>
  <h1>QUIZ</h1>
  <div id="answers">
    <div class="barcelona">
      <p> Antoni Gaudi </p>
    </div>
    <div class="paris">
      <p> Champ Elysees </p>
    </div>
    <div class="london">
      <p> Tate Modern </p>
    </div>
    <div class="barcelona">
      <p> Sagrada Familia </p>
    </div>
    <div class="paris">
      <p> Montmartre </p>
    </div>
    <div class="ny">
      <p> Fifth Avenue </p>
    </div>
    <div class="barcelona">
      <p> Paella </p>
    </div>
    <div class="barcelona">
      <p> La Rambla </p>
    </div>
    <div class="london">
      <p> Piccadilly Circus </p>
    </div>
    <div class="paris">
      <p> Mona Lisa </p>
    </div>
    <div class="ny">
      <p> Empire State Building </p>
    </div>
    <div class="ny">
      <p> Broadway </p>
    </div>
    <div class="paris">
      <p> Musée d'Orsay </p>
    </div>
    <div class="ny">
      <p> Wall Street </p>
    </div>
    <div class="london">
      <p> Camden Town </p>
    </div>
    <div class="ny">
      <p> Big Apple </p>
    </div>
    <div class="barcelona">
      <p> La Boqueria </p>
    </div>
  </div>


  <div id="box">
    <div class="paris">
      <p> PARIS </p>
    </div>
    <div class="ny">
      <p> NY </p>
    </div>
    <div class="london">
      <p> LONDON </p>
    </div>
    <div class="barcelona">
      <p> BARCELONA </p>
    </div>
</body>

</html>

Answer №1

Snippet from the jQuery UI API guide for droppable:

drop( event, ui )

  • event
  • ui
    • draggable: A jQuery object representing the draggable element.
    • helper: A jQuery object representing the helper being dragged.
    • position: Current CSS position of the draggable helper as { top, left } object.
    • offset: Current offset position of the draggable helper as { top, left } object.

You are probably aware that this pertains to the droppable element, but now you also have access to the draggable. The "helper" in jQuery refers to the element following the cursor. By default, these two are the same, but you could opt to have the draggable remain stationary until dropped while a ghostly clone follows your cursor.

Instead of assigning a class to the draggable and checking it in the drop event using a script like this...

const categories = ["paris", "ny", "london", "barcelona"];

$(function() {
  $("#answers div").draggable();
  $("#box div").droppable({
    drop: function(event, ui) {
      const $this = $(this);
      
      if (categories.some(c => $this.hasClass(c) && ui.draggable.hasClass(c))) {
        $this
          .addClass("ui-state-highlight")
          .find("p")
          .html("Valid :)");
      } else {
        $this
          .addClass("ui-state-highlight")
          .find("p")
          .html("Invalid :(");
      }      
    }
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>QUIZ</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>

<body>
  <h1>QUIZ</h1>
  <div id="answers">
    <div class="barcelona">
      <p> Antoni Gaudi </p>
    </div>
    <div class="paris">
      <p> Champ Elysees </p>
    </div>
    <div class="london">
      <p> Tate Modern </p>
    </div>
    <div class="ny">
      <p> Fifth Avenue </p>
    </div>
  </div>

  <div id="box">
    <div class="paris">
      <p> PARIS </p>
    </div>
    <div class="ny">
      <p> NY </p>
    </div>
    <div class="london">
      <p> LONDON </p>
    </div>
    <div class="barcelona">
      <p> BARCELONA </p>
    </div>
  </div>
</body>

</html>

It's advisable to think ahead for the future. At some point, you might want to store puzzles in JavaScript.

[
  { category: "Paris", answers: ["Champ Elysees", "Montmartre"] },
  { category: "NY", answers: ["Big Apple", "Broadway"] }
]

This way, you could automatically generate the HTML for puzzles and store the draggable and droppable widgets within each category. Consider the following approach:

categories.forEach(c => {
  c.droppable = createDroppable(c.category);
  c.draggables = c.answers.map(answer => createDraggable(answer));
});

Then, you could compare the draggable and droppable elements by identity without relying on attributes. While I'm not extensively familiar with jQuery, I believe this can be achieved using the is method.

// inside the drop event
const category = categories.find(c => $(this).is(c.droppable));
if (category.draggables.some(answer => ui.draggable.is(answer)) {
  // this answer is correct!
}

Answer №2

To identify the class of an element and verify if it is included in the current element, you can leverage ui.draggable:

$( function() {
  $( "#answers div" ).draggable();
  $( "#box div" ).droppable({
    drop: function( event, ui ) {
      var dropped = $(this).attr('class').split(' ')[0];
      if(ui.draggable.attr('class').split(' ').includes(dropped)){
        $( this )
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
      } 
    }
  });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<h1>QUIZ</h1>


<div id = "answers">
  <div class = "barcelona"><p> Antoni Gaudi </p></div>
  <div class = "paris"><p> Champ Elysees </p></div>
  <div class = "london"><p> Tate Modern </p></div>
  <div class = "barcelona"><p> Sagrada Familia </p></div>
  <div class = "paris"><p> Montmartre </p></div>
  <div class = "ny"><p> Fifth Avenue </p></div>
  <div class = "barcelona"><p> Paella </p></div>
  <div class = "barcelona"><p> La Rambla </p></div>
  <div class = "london"><p> Piccadilly Circus </p></div>
  <div class = "paris"><p> Mona Lisa </p></div>
  <div class = "ny"><p> Empire State Building </p></div>
  <div class = "ny"><p> Broadway </p></div>
  <div class = "paris"><p> Musée d'Orsay </p></div>
  <div class = "ny"><p> Wall Street </p></div>
  <div class = "london"><p> Camden Town </p></div>
  <div class = "ny"><p> Big Apple </p></div>
  <div class = "barcelona"><p> La Boqueria </p></div>
</div>


<div id = "box">
  <div class = "paris"><p> PARIS </p></div>
  <div class = "ny"><p> NY </p></div>
  <div class = "london"><p> LONDON </p></div>
  <div class = "barcelona"><p> BARCELONA </p></div>
</div>

Instead of using classes for comparison, a better approach is to use custom attributes as recommended in the comment section:

$( function() {
  $( "#answers div" ).draggable();
  $( "#box div" ).droppable({
    drop: function( event, ui ) {
      var dropped = $(this).data('city');
      if(ui.draggable.data('city') == dropped){
        $( this )
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
      } 
    }
  });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<h1>QUIZ</h1>


<div id = "answers">
  <div data-city="barcelona"><p> Antoni Gaudi </p></div>
  <div data-city="paris"><p> Champ Elysees </p></div>
  <div data-city="london"><p> Tate Modern </p></div>
  <div data-city="barcelona"><p> Sagrada Familia </p></div>
  <div data-city="paris"><p> Montmartre </p></div>
  <div data-city="ny"><p> Fifth Avenue </p></div>
  <div data-city="barcelona"><p> Paella </p></div>
  <div data-city="barcelona"><p> La Rambla </p></div>
  <div data-city="london"><p> Piccadilly Circus </p></div>
  <div data-city="paris"><p> Mona Lisa </p></div>
  <div data-city="ny"><p> Empire State Building </p></div>
  <div data-city="ny"><p> Broadway </p></div>
  <div data-city="paris"><p> Musée d'Orsay </p></div>
  <div data-city="ny"><p> Wall Street </p></div>
  <div data-city="london"><p> Camden Town </p></div>
  <div data-city="ny"><p> Big Apple </p></div>
  <div data-city="barcelona"><p> La Boqueria </p></div>
</div>


<div id="box">
  <div data-city="paris"><p> PARIS </p></div>
  <div data-city="ny"><p> NY </p></div>
  <div data-city="london"><p> LONDON </p></div>
  <div data-city="barcelona"><p> BARCELONA </p></div>
</div>

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 is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Improving website speed and efficiency with asynchronous loading using AddThis

After following the instructions in the guide, I was able to trigger addthis using ajax, but it seems to only work on one specific location. For example, on the html index page 'index.php', <a href="#" class="load">click to load</a> ...

Creating layered images with CSS Grid

Visit this link for more details I've been attempting to create an overlap effect with 3 photos using CSS Grid. My desired outcome looks like this: Click here to see the desired result I followed tutorials that demonstrate the same method, but unfo ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...

Retrieve the erased document using Google's cache feature

After accidentally overwriting my .php web document file with an old version, I attempted to access the cached copy on Google. The only thing I could find was the HTML scripts, as the PHP coding was not visible. Now I am seeking a method to recover the e ...

What is the best way to predefine a value for a checkbox in Angular?

Here is the code snippet I am currently using: <input type="checkbox" [(ngModel)]="i.checkt" [ngModelOptions]= {standalone:true} (change)="recovery(i.checkt,i.TherapeuticArea)"> {{i.TherapeuticArea}} I have encountered an issue where setting stan ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

Unable to display the value of a server-side li element using JQuery

I am trying to retrieve values from a ul list that is populated from the database using server-side code. I want to display the li value in a jquery alert function, but it doesn't seem to be working as expected. Strangely, the same function works perf ...

Delivering Access data in HTML format via email

In my MS Access database, I have a report that combines client records from one table (including email addresses) with grouped records fetched from other tables using a Query. I want to send this report directly to each client via email, within the body o ...

Issue with nextElementSibling not applying CSS style

My current issue revolves around a button that is designed to open or close a collapsible div. The HTML structure of this element looks like the following: <div class='outer-collapsible'> <button type='button' class='col ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

Encountered an error: "Type error undefined" while attempting to populate a form using AJAX and JSON

Upon inspecting the development console, it's clear that my AJAX request was successful and I've received the necessary JSON data. However, I'm struggling to display it correctly as I keep encountering the error below: Uncaught TypeError: C ...

How to pass the id value between pages in web developmentactics?

I've been struggling to call the id value of one page in another for a while now. I assigned the id value "addedcart" to the form and tried to call it in my PHP code, but no cart value is being displayed. I'm not sure if I am calling the id corre ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

What is the title of a document that is linked behind an HTML link?

I am seeking a way to automatically retrieve documents from web pages using a Python script. The links in the HTML pages appear as follows: href="https://foo.bar/view.php?id=123456" When clicked on in a web browser, these links open the document with its ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Issue encountered during Node.js installation

Every time I attempt to install node js, I encounter the following errors: C:\Users\Administrator>cd C:/xampp/htdocs/chat C:\xampp\htdocs\chat>npm install npm WARN package.json <a href="/cdn-cgi/l/email-protection" class ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...