How to press the button again to cancel the action or add a function that will return these items back to their places? Actually the transfer of elements occurs when you click to swap places on this site serjo96.imtqy.com/matrix

$(document).on("click",".change-mtrx", function(){ $('.matrix_a').appendTo('.matrix_b_cover'); $(".matrix_b").appendTo(".matrix_a_cover"); }); 
  • What action should you cancel (by example)? And so at the moment everything rules the states, for example in ReactJS this is Redux with the Immutable model. It is easy to wind back events there - Vasily Barbashev
  • Cancel the transfer of items that occur when you click - Drop
  • Add the initial html markup to the question so that you can see where the .matrix_a , .matrix_b , .matrix_b_cover , .matrix_a_cover and where they should return - Grundy
  • Added a link to the project - Drop
  • Add markup directly to the question - Grundy

1 answer 1

You can add and remove auxiliary class. And check its availability.

  $('.change-mtrx').click(function () { var matrixA = $('.matrix_a'); var matrixB = $('.matrix_b'); if (!matrixA || !matrixB) return false; if (matrixA .hasClass('moved')) { matrixA.appendTo($('.matrix_a_cover')); matrixA.removeClass('moved'); } else { matrixA.appendTo($('.matrix_b_cover')); matrixA.addClass('moved'); }; if (matrixB.hasClass('moved')) { matrixB.appendTo($('.matrix_b_cover')); matrixB.removeClass('moved'); } else { matrixB.appendTo($('.matrix_a_cover')); matrixB.addClass('moved'); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="matrix_a_cover"><p>matrix_a_cover</p></div> <div class="matrix_a"><p>matrix_a</p></div> <div class="matrix_b_cover"><p>matrix_b_cover</p></div> <div class="matrix_b"><p>matrix_b</p></div> <button class="change-mtrx">change-mtrx</button> 

  • one
    you are doing very badly, you need to re-select a sample of elements into a variable, and you are looking for 2 elements per page 5 times, do you think this is good? - Vasily Barbashev
  • @ Vasily Barbashev Agreed. Thanks for editing. - Gleb Kemarsky
  • And if it is even easier to do, toggleclass on the button that we press and then arrange to check this class and then the transfer? - Drop
  • @Drop The main thing is that the solution is consistent with the mechanics. If all the blocks change in chorus, and the button changes once and after moving the blocks, it is logical to use the class on the button. If several buttons control the blocks and after moving blocks, the indent, background or something else in the styles changes, then the class for the blocks is suggested. - Gleb Kemarsky
  • @Drop I saw a link to the project. If in serjo96.imtqy.com/matrix/js/style.js replace $(document).on("click",".change-mtrx", function(){ $('.matrix_a').appendTo('.matrix_b_cover'); $(".matrix_b").appendTo(".matrix_a_cover"); }); On the code from the answer, the switch will work in both directions. - Gleb Kemarsky