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

Filling HTML5 Datepicker Using Information from a Model

Currently, I am in the process of developing a basic scheduling application for a project. To simplify the task of selecting start and end times/dates for our events, we have included a simple DateTime picker in the source code: <input type="datetime-l ...

Passing PHP information into a JavaScript array

I am facing an issue with my PHP file where I am fetching data from a MySQL database and storing it in a PHP array. I am then trying to output this data as a JS array but for some reason, I am unable to access the JS variable in my JS files. Here is the c ...

JQUERY confirm dialog causing AJAX malfunction

I am encountering an issue where I am trying to execute an ajax function only after the user confirms a dialogue using JQUERY confirm. Strangely, when I include the confirmation step, my code throws an error and does not function properly. It's worth ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

the specified computed property does not have a value assigned

Issue with the Computed name Property in a Component <template> <div class="person"> <p>{{name}}</p> </div> </template> <script> export default { name: 'person', data () { return ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Sending data from a server using Node.js, Express, and JQuery through a POST request

As someone new to web development, I'm experimenting with Node.js, Express, and EJS to create a weather application that displays the temperature based on a zipcode. So far, retrieving and showing the temperature has been successful. However, I want t ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

The execution of a function in PHP is determined by the data passed from Angular

I've encountered a new challenge while working on web development and would greatly appreciate some assistance. Currently, I have several buttons that need to execute different functions when clicked, such as ng-click='loadA', ng-click=&apos ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

Switching from React version 15.6.2 to 16 results in disruptions to the functionality of the web

Currently, I am encountering an issue where none of my index.js files are rendering. After using the react-scripts to build my web application in version 16.2.0, I receive an error stating that r.PropTypes is undefined when trying to access the localhost a ...

Trigger a click event on a div element that is nested within a form

Having trouble displaying an alert when clicking on a disabled button because the user needs to first click on a terms checkbox. Here's my jQuery code: $('#divButton').on("click", function() { if ($('#buybutton').prop('d ...

Performing an AJAX request within another AJAX request using jQuery

$.ajax({ type: 'POST', url: searchpage, dataType: "json", data: { id: id }, success: function(data) { var id1 = []; for(var i = 0; i < data.length; i++){ id1 .push({ ...

Adjust the background color of alternate elements

I am looking to customize the background colors of every other element within the structure provided below: <div class="dets"> <div>Simple Layout</div> <div>Few Pictures/Links</div> <div>Element Uniformity</div> ...

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

The initial option in the jQuery dropdown list is populated with `[object Object]`

I am encountering a strange issue with a jQuery function that is supposed to populate a select list. Here is the AJAX call: loadShowAllReports = function() { $.ajax({ url: "cfc/Reports.cfc" , type: "get" , dataType: "json" ...

Using v-model with an input file is not supported

Is there a solution for not being able to use v-model in an input tag with type="file"? Here is an example of the HTML code causing this issue: <input v-model="imageReference" type="file" name="file"/> ...

The presence of element a within the element ul is not permitted in this particular scenario. Additional errors from this section will not be displayed

Having trouble with this code snippet: <nav role="navigation"> <div id="menuToggle"> <input type="checkbox"/> <span></span> <span></span> <span></span> ...

Cross-border PHP document

Each PHP page must begin with the following code: <?php $host="localhost"; // Host name $username=""; // MySQL username $password=""; // MySQL password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select datab ...