JavaScript - rearrange letters in a word by dragging them

Currently, I am developing a browser game called "WordShuffle".
(The words are in German for testing purposes, if you want to play)

My progress is coming along nicely, but I have decided to change the gameplay mechanics. Instead of typing your guess into a text field to solve the word, I want players to rearrange the letters by dragging and dropping them into the correct order.

Since I am not very skilled in JavaScript (which I believe would work best for this feature), I need some help with that aspect. However, I do need to be able to extract a value from the rearranged word in order to compare it to the correct answer. A submit button will then pass this value.

I created concept art to provide a visual representation:
https://i.sstatic.net/SAyIV.png

https://i.sstatic.net/IdpxO.png

https://i.sstatic.net/ZsV5U.png

https://i.sstatic.net/vyeN3.png

Answer №1

Check out this demo showcasing the use of jquery-ui sortable and implementing the Fisher-Yates shuffle algorithm:

$(function() {
  $("#wordblock").sortable();
  $("#wordblock").disableSelection();

  const word = 'example';
  let d_word = word.split('');
  shuffle(d_word);

  const lis = [];
  for (let i = 0; i < d_word.length; i++) {
    lis.push('<li class="ui-state-default">' + d_word[i] + '</li>')
  }

  $('#wordblock').html(lis.join(''));

  $('#wordblock').mouseup(function() {
    setTimeout(() => {
      let r_word = '';
      $('#wordblock>li').each(function(e) {
        r_word += $(this).text();
      });
      if (r_word == word) {
        console.log("YOU FOUND IT! : " + r_word);
      } else {
        console.log("Keep trying!");
      }
    }, 0);
  });

});

function shuffle(a, b, c, d) {
  c = a.length;
  while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}
#wordblock {
  list-style-type: none;
  margin: 0;
  padding: 0;

  /* prevent text selection */
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}  


#wordblock li {
  margin: 3px 3px 3px 0;
  padding: 1px;
  width: 40px;
  float: left;
  font-size: 3em;
  text-align: center;
  cursor: pointer;
  font-family: arial;
  background-color: rgb(0,100,155);
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<ul id="wordblock">
</ul>

Answer №2

If you're looking for a way to create a sortable word using jQuery, you can utilize jQuery's Sortable feature which can be found here.

By implementing Sortable, you can arrange each letter of a word in separate div elements. Take a look at this example:

HTML:

<div class="word">
    <div>G</div>
    <div>A</div>
    <div>M</div>
    <div>E</div>
</div>

JS:

$(function () {
    $(".word").sortable();
});

http://jsfiddle.net/dbp2988e/

To complete this task, you would need to iterate over the divs within the main word div, extract each div's content (using .html() method), concatenate them into a single string, and then compare it against the secret word.

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

Tips for ensuring all data is properly set before saving in mongoose

Struggling to update undefined or defined values in Mongoose due to the need to await their assignment. It seems like the code is not saving the data because USER.save() is executed before the values are set. How can I ensure that the data is updated/set ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

Tips for preloading a small placeholder image before the main content is loaded

After browsing , I noticed an interesting image loading style. The website initially shows a patterned image before revealing the actual content. This method creates visually appealing content while waiting for the entire webpage to load. Upon inspecting ...

What are the steps to utilize webpack for refreshing the script tag in a jade file?

Can webpack be used to automatically update the script tag in a jade/pug template to point to the minified and cache-busted JS bundle? Most examples I've come across demonstrate how plugins can be used to convert the jade template to HTML, but I am us ...

Using jQuery to move a div to a specific location on the page

Is there a way to translate the position of div x and y using Jquery that is compatible with all browsers, such as IE 7, IE8, IE9, and IE10? I have attempted the following: <div id="s1" style="-ms-transform:translate(159,430)"> hello ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Checking for mouse button press during Firefox mouse movement

Trying to drag a div without needing to add a mouseup function to avoid potential bugs if the user's mouse is outside the window. Tested with chrome, IE and firefox - "e.which" works fine in IE and chrome but firefox retains the last clicked button s ...

Attempting to make a slightly bigger than usual AXIOS.post request to a .NET Web API

When attempting to perform an AXIOS.post in a Vue.JS application, the process fails when exceeding about 1500 characters. Instead of reaching the Web API, it goes directly to the error area. Typically, this function calls a .Net Web API that generates a MS ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: https://i.sstatic.net/pcLQX.png Query How can I enable real-time inspections to occur immediately? (I ...

What is the best way to hide the next/previous tabs once the jQuery dataTable has been set up using jSON data

Setting up a jQuery table using JSON data. Despite knowing that there will only be one row, the next/previous tabs are still displayed after the table. Is there a way to remove them? Here is the code for the table: table = $("#retrievedTable").dataTabl ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

Displaying the currently logged in user's name with NodeJS/ExpressJS/Passport

In my quest to showcase the username for logged-in users (function 3), I encountered a dilemma. Initially, only function 1 existed in my codebase. To address this issue, I made modifications and introduced function 2 to facilitate displaying usernames of a ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Utilizing Angular JavaScript for detecting and setting up JDK installations

I am working on an application that requires the installation of Java JDK. Therefore, I need to develop a detection function for JDK in the system. If it is not found, I plan to install it using a setup provided by me and also set it in the system variabl ...

Troubleshooting: AngularJS ng-repeat not rendering JSON data

I have successfully retrieved JSON data from a database using PDO in Angular. The data is being returned as expected when I encode it to JSON. However, I am facing an issue with displaying the data using ng-repeat in Angular. Although the div elements are ...

Utilizing JQuery for retrieving a filename

I have a unique file upload button on my website. To provide the user with visual feedback about their chosen file, I modify the html of a div to display the file name. My jquery code is as follows: $("input[type=file]").change(function() { var filen ...

Safari failing to load JavaScript on live website

While JavaScript functions correctly both locally and in production on Chrome, I am facing issues when trying to run it on Safari. Despite having JavaScript enabled on Safari and it working fine locally, it fails to work on the production environment. This ...

What are the methods for defining fontSize and fontWeight in Quasar using :table-header-style?

Struggling to adjust the font size and weight in the header of a q-table component using Quasar. Surprisingly, changes to font color and background color are effective, but the size and weight remain unchanged. ...