`How can I use JavaScript to display a modal?`

I am currently a student immersing myself in the world of coding, particularly focusing on learning javascript/jquery. In my recent project, I have developed a chess game using RoR and now I am tackling the promotion move. The idea is that when a Pawn piece reaches the opposite end of the board, a modal should pop up, allowing the player to choose a new piece to replace the pawn. I already have a modal set up on the front end that should trigger automatically once the conditions are met. However, despite creating a function called is_pawn_promotion to handle this, the modal fails to open on its own. I suspect that the is_pawn_promotion function is not called correctly. I've attempted to rearrange the code for calling the openModal function, but to no avail. Any guidance or assistance would be highly appreciated, and I hope my description of the issue is clear enough.

Below is the JS file containing the is_pawn_promotion function. The file also includes the openModal function that I'm trying to execute in order to open the modal.

$( function() {
  $( ".piece" ).draggable({
    snap: ".piece-square",
    grid: [60, 60],
    containment: ".game-board",
  });

  $( ".piece-square" ).droppable({
    accept: ".piece",
    drop: function( event, ui ) {
      var x = $(event.target).data('x');
      var y = $(event.target).data('y');
      var urlUpdatePath = $('.ui-draggable-dragging').data('url');
      var is_pawn_promotion = function() {
        return $(".piece") === 'Pawn' &&
          (y === 0 || y === 7); 
      };

      var sendAJAXRequest = function(x, y, type) {
        $.ajax({
          type: 'PUT',
          url: urlUpdatePath,
          data: { piece: { x_position: x, y_position: y, piece_type: type} },
          success: function(response) {
            if(response === 'OK') {
              console.log(response);
            } else {
              alert(response);
            }
          }
        });
      };

      if (is_pawn_promotion()) {
        openModal();
        var promoSubmitButton = $(".promo-selection-submit");
        promoSubmitButton.on('click', function() {
          var type = $('.promo-selection.input(selected)').val();
          sendAJAXRequest(x, y, type);
        });
      } else { 
        sendAJAXRequest(x, y);
      }
    }
  });
});

var openModal = function() {

  // Change modal-state checkbox to checked
  $("#promo-modal").prop("checked", true);

  if ($("#promo-modal").is(":checked")) {
    $("body").addClass("modal-open");
  } else {
    $("body").removeClass("modal-open");
  }

  $(".modal-fade-screen, .modal-close").on("click", function() {
    $(".modal-state:checked").prop("checked", false).change();
  });

  $(".modal-inner").on("click", function(e) {
    e.stopPropagation();
  });
};

The Modal

<div class="modal">
  <input class="modal-state" id="promo-modal" type="checkbox" />
  <div class="modal-fade-screen">
    <div class="modal-inner">
      <div class="modal-close" for="promo-modal"></div>
      <div class="promo-modal-text">
        <h1>Pawn Promotion!</h1>
        <h1>Make your selection: </h1>
      </div>
      <form action="#" class="pawn-promotion">
        <div class="promo-selection-container">
          <% [Queen, Knight, Bishop, Rook].each do |piece_type| %>
            <div class="promo-selection">
              <label>
                <%= image_tag(piece_type.new(color: current_color).piece_image) %>
                <%= piece_type.name %>
                <input type="radio" name="promo-piece" value="<%= piece_type.name %>">
              </label>
            </div>
          <% end %>  
        </div>
        <br/>
        <div class="promo-selection-submit">
          <input type="submit">
        </div>
      </form>
    </div>
  </div>
</div>

Answer №1

Attempting to execute the function before it is declared. Consider relocating the function declaration.

Answer №2

After some trial and error, I was able to come up with a solution on my own. The main issue was with how the is_pawn_promotion function was defined. Here is the corrected version:

var is_pawn_promotion = function() {
  return ui.draggable.data('pieceType') === 'Pawn' &&
    (y === 0 || y === 7); 
};

I also made sure to include the data-piece-type property for the piece in the view like this:

<div class="piece" data-url="<%= game_piece_path(piece.game, piece)%>" data-piece-type="<%= piece.piece_type %>">
  <%= image_tag(piece.piece_image) %>
</div>

Now, whenever a pawn piece is in a position to be promoted, the modal will open as intended.

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

Error triggered by .click() leading to confirmation() being repeated and resulting in duplicated data

Creating a Functional CRUD Application After successfully implementing a CRUD CMS using AJAX, everything was running smoothly until I introduced pagination with click ajax events. This script, which I will share below, seems to be causing some issues. +- ...

Issue with Heroku deployment: unable to locate JavaScript file

I encountered an issue while deploying my node.js app. Everything seemed to be working fine but it couldn't locate the JavaScript files. The error message displayed was: proove.herokuapp.com/:16 GET 404 (Not Found) Here is the server.js code snip ...

Resuming AJAX requests after being aborted

Hey everyone, I'm curious to know if it's possible to resume interrupted ajax requests. I have an array of ajax calls stored as defferreds like this: var defferreds = []; defferreds.push( $soap.ajax({ type: "POST", dataType: ...

Adjusting image size as you scroll

Hello everyone, I am currently working on coding a website logo that decreases in size as the user scrolls down, similar to the effect seen on this website: . I am relatively new to HTML and was wondering if there are any specific commands or techniques th ...

Using Jquery with CakePHP

What is the best way to incorporate jQuery into PHP? I have included an external JavaScript file in my default.ctp file. It works fine on my localhost, but it’s not working on the main server. Any suggestions? ...

What can be done to improve the elegance of this jQuery function?

I am facing an issue on my webpage where I have a drop-down select box with a default value of (empty). The problem arises when the user selects an entry, and the appropriate form for that entry type should be displayed. However, there are a couple of iss ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

Transitioning from feelings to sewing: incorporate a duo of properties within variations and breakpoints

I was thinking about how to convert this styled-emotion code into stitches. Essentially, I need to handle the onlyShowOnDesktop and breakpoint props. The definition of breakpoint is as follows: const breakpoint = isTopNavigationBreakPoint ? theme.defaultB ...

Delay problem caused by setTimeout

I am developing a version of the "Game of Life" using javascript. I have successfully implemented all the logic within a function named doGeneration(). When calling this function repetitively from the console, everything works as expected. However, when at ...

dealing with errors coming from a child asynchronous callback function

function main(){ try { subCallbackFunction(1,(err,res) =>{ if(err){ throw Error(err); } }) } catch (e) { /// Handling error from subCallbackFunction inside this catch block ////// conso ...

In React Native, changing the translation of an element causes it to shift below all other elements, regardless of

Check out this sandbox project: I'm trying to create a simple animation using translation in React Native, but I'm facing an issue where when I move the element to the right and down, it goes under other elements. However, if I move it left and ...

Tips for implementing ngChange within a personalized directive

Looking to create a directive for a toggle button, here is the code I want to include in the directive: <div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}"> <button class="true" ng-click="toggleTrue ...

The positioning of the menu icons varies

When it comes to displaying the search icon in the WordPress toggle bar, I use a custom JavaScript file. This setup is mainly focused on website design and menu functionality. Additionally, I have integrated a newsletter subscription plugin for managing su ...

What is the reason for the successful addition of a list item, using dynamic methods, in Chrome and Firefox while encountering issues in

I have encountered an issue with my jQuery code that works perfectly fine in Firefox and Chrome but fails to work in Internet Explorer 8 (I haven't tested it on other versions of IE). It is important to note that Internet Explorer is running in standa ...

Is there a case of Bootstrap Offcanvas fade appearing twice in various sections of the website?

Currently in the process of updating my website using Ruby on Rails, I was given the task of integrating Bootstrap instead of using custom CSS styling. While this change posed no issue, a problem arose when I implemented the Offcanvas menu from Bootstrap. ...

jQuery ajax functions only function properly in Internet Explorer

Having an issue with my multilingual MVC 3 application. I am using a dropdownlist to switch languages by saving the value into a cookie and session. The problem is that it only works in IE. When I reload the site or close Firefox or Chrome, the language ch ...

The callback function does not get invoked when using JSONP

Learning jsonP has been a challenge for me as I am relatively new to it. I have done my research by reading various articles but when trying out a simple example, the callback function fails to execute. Surprisingly, there are no errors or exceptions logge ...

Creating a Form with Table-like Alignment Using Div Tags

Take a look at my code: <div> <label>First Name</label><input type="text" id='first_name'/><br /> <label>Last Name</label><input type="text" id='last_name'/><br /> <l ...

What's the best way to fill in content for textarea and radio buttons?

I retrieved data from a database and stored it in the variable $tableRe. Now, I need to display these values in a textarea and also check the radio button. Below is my code snippet: $sql = "select (address, gender) from stud table"; if($result=mysqli_que ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...