relocate & adjust the position of an element beneath a sibling element in the HTML code

My goal is to align an <li> element with the exact same position as the preceding <li> on the webpage. I am utilizing the jQuery function .position() for this purpose.

Whenever a left swipe or drag action is detected on my <li> component, after a timeout of 1000ms, I want to relocate the <li> to the position of the last item marked as "stackPos"

I have set up the final element as follows:

$('ul.feed li').last().addClass('stack');

Retrieving its position:

var stackPos = $('ul.feed li.stack').position();

Adjusting the position post timeout:

setTimeout(function(){
   $(this).css({top: stackPos.top, left: stackPos.left});
}, 1000);

An attempt to log a message using console.log() after the timeout displays without any updates in the positioning.

For complete code and demo example, visit - https://jsfiddle.net/myz3czro/32/

$( document ).ready(function() {

$('ul.feed li').first().addClass('top');
$('ul.feed li').last().addClass('stack');    
var touch = $('ul.feed li.top').offset().left;
    var pullLeftLimit = touch - 15;
var stackPos = $('ul.feed li.stack').position();
console.log('Stack Of Cards at: ' + stackPos.left + ' top: ' + stackPos.top);

$($('.content ul li').get().reverse()).each(function(i, el) {
  $(el).css('z-index', i + 1);
  var degrees = Math.floor((Math.random() * 20) - 10);
  $(el).css({
    '-webkit-transform' : 'rotate('+degrees+'deg)',
    '-moz-transform' : 'rotate('+degrees+'deg)',  
    '-ms-transform' : 'rotate('+degrees+'deg)',  
    '-o-transform' : 'rotate('+degrees+'deg)',  
    'transform' : 'rotate('+degrees+'deg)',  
    'zoom' : 1
    });
});

$( function() {
  $( ".draggable" ).draggable({
    axis: "x",
    drag: function( event, ui ) {  
      var newTouch = $('ul.feed li.top').offset().left;

      if(pullLeftLimit > newTouch){
        $(this).addClass('swipe');
        setTimeout(function(){
          $(this).css({top: stackPos.top, left: stackPos.left});
        }, 1000);
      }
    }
  });
});

$(function(){
  $( ".cover" ).on( "swipe", swipeHandler );   
  function swipeHandler( event ){
    $( this ).parent().addClass( "swipe" );
  }
});    

function stackMe(){
    console.log('test');
}

  });

Answer №1

There seems to be a slight error in the setTimeout function, but overall, for optimal performance, I would opt for using the draggable.stop handler to manage the card repositioning.

In the end, the main repositioning function appears like this:

$(function() {
  $(".draggable").draggable({
    axis: "x",
    stop: function(event, ui) {
      var self = this;
      setTimeout(function() {
        var stack = [];
        $(".content ul li").each(function(i, el) {
          stack.push($(el).css("z-index"));
        });
        stack.unshift(stack.pop());
        $(".content ul li").each(function(i, el) {
          $(el).css('z-index', stack[i]);
        });
        $(self).removeClass('swipe').css({
          top: stackPos.top,
          left: stackPos.left
        });
      }, 1000);
    },
    drag: function(event, ui) {
      var newTouch = $('ul.feed li.top').offset().left;
      if (pullLeftLimit > newTouch) {
        $(this).addClass('swipe');
      }
    }
  });
});

Following your card naming convention, the z-index will SHIFT as shown below:

Card a: z-index 5 --> becomes 1
Card b: z-index 4 --> becomes 5
Card c: z-index 3 --> becomes 4
Card d: z-index 2 --> becomes 3
Card e: z-index 1 --> becomes 2

...and so forth.

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

I am struggling to make the horizontal scroll and fixed column features work in dataTables. The rendering seems to be inconsistent across different platforms. Can anyone help me figure out what I am doing incorrectly?

I've dedicated countless hours to unraveling this conundrum. I'm in urgent need of creating a table that mirrors the layout displayed on this webpage: https://datatables.net/extensions/fixedcolumns/ The desired functionality involves both verti ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

Transfer information to the form through a hyperlink

I need help with a script that sends data to a form when a link is clicked. What I'm trying to achieve is to have the data appear in the form when the user clicks the link below, which is generated from a database. <div id="menu_bar" region="west ...

Using Jquery to iterate through a PHP array, calling an API to fetch data, and then storing the results

I am working with a PHP array called startups[] that contains 36000 startup names. My goal is to create a URL API endpoint using these names. Despite my efforts, I have been unsuccessful in utilizing jQuery to iterate through this PHP array and for each o ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Calculating the sum of all words that have been successfully finished

My spelling game includes words of different sizes ranging from 3 to 6 letters. Once a certain number of words are completed in the grid, the remaining grid fades away. Instead of only considering one word size at a time, I want the game to calculate the t ...

Transitioning the slider after displaying the full image

Currently, I am utilizing the Supersize slider for my project. However, I have encountered an issue where if an image is large and takes time to load, the slider transitions to a new image before the previous one has fully loaded. I am looking to impleme ...

What could be the reason behind my inability to initiate this PHP file through jQuery/AJAX?

I'm experiencing an issue with a piece of PHP code (located at ../wp-content/plugins/freework/fw-freework.php). <div id="new-concept-form"> <form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role ...

The onClick function for the "div" element is failing to append

I am currently working on a project that involves searching for strings in a database and then appending the selected string to a text box. So far, I have been successful in retrieving the search results from the database and appending them below the text ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

Tips for automatically inserting a "read more" link once text exceeds a certain character count

Currently utilizing an open-source code to fetch Google reviews, but facing an issue with long reviews. They are messing up the layout of my site. I need to limit the characters displayed for each review and provide an option for users to read the full rev ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

Steps for inserting an image:

Looking for help adding a static header image to a simple HTML page that contains two div tags: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd"> <html> <head> ...

What steps do I need to take in order to modify information within a table using Symfony?

Working on my Symfony project, I frequently need to display various views in table format. I wish I could easily update the data by clicking on table cells, entering new information, and saving it dynamically. After exploring jqGrid, DataTable with jEdit ...

Obtaining information from the HttpServletResponse through an AJAX form

In my "first.jsp", there is a form containing hidden input values and pointing to another jsp file. <form id="popupForm" name="popupForm" action="<%= cqRequest.externalizeHref(handle) %>" method="post"> <input type= ...