• 0

[jQuery] Swap Element Positions


Question

18 answers to this question

Recommended Posts

  • 0

Something along the lines of

	(function( $ ){
		$.fn.swap = function(other,speed) {
			//get the position
			var position1 = this.offset();
			var position2 = other.offset();

			//position this where it is
			this.css({
				top: position1.top + 'px',
				left: position1.left + 'px',
				position: 'absolute'
			});

			//position the other element where it is
			other.css({
				top: position2.top + 'px',
				left: position2.left + 'px',
				position: 'absolute'
			});

			this.animate({
				'top': position2.top + 'px',
				'left': position2.left + 'px'
			}, speed, function() {
					// Animation complete.
			});

			other.animate({
				'top': position1.top + 'px',
				'left': position1.left + 'px'
			}, speed, function() {
				// Animation complete.
			});
		};
	})( jQuery );

	//add animate when we clicky trigger
	$('#trigger').click(function(e) {
					$('#element1').swap($('#element2'),300);
				});

  • 0

$(document).ready(function()
{
	$('#startAnimation').click(function()
	{
		$('#item1').animate({
			top: $('.item:eq(1)').css('top'),
			left: $('.item:eq(1)').css('left')
		}, 500);

		$('#item2').animate({
			top: $('.item:eq(0)').css('top'),
			left: $('.item:eq(0)').css('left')
		}, 500);
	});
});

Was bored in work and remember seeing this topic before I left this morning... said i'd give it a go. Beaten to the punch it seems :p

  • 0
  On 12/08/2011 at 10:10, Quigley Guy said:

$(document).ready(function()
{
	$('#startAnimation').click(function()
	{
		$('#item1').animate({
			top: $('.item:eq(1)').css('top'),
			left: $('.item:eq(1)').css('left')
		}, 500);

		$('#item2').animate({
			top: $('.item:eq(0)').css('top'),
			left: $('.item:eq(0)').css('left')
		}, 500);
	});
});

Was bored in work and remember seeing this topic before I left this morning... said i'd give it a go. Beaten to the punch it seems :p

I also saw this at work and though it would be a good excuse to finally check out jQuery. Made me wanna marry jQuery though, and divorce Dojo

  • 0

So hears my code so far: http://jsfiddle.net/LYc3E/3/

I've not been able to include all your cool visual animations because I've been having problems with the absolute positioning.

Can someone try to put that in for me?

Remember, Paragraph 1 and Paragraph 2 shoudl not jump or jitter, if you don't know the height or the top location of the DIVs.

  • 0

$(document).ready(function()
{
    var animationSteps = 0;
    var animationInProgress = false;

    $('#item-queue').css('height', $('#item-queue').height());

    $('#item-queue .item').each(function()
    {
        var top = 0;

        $(this).prevAll().each(function() {
            top += $(this).outerHeight();
        });

        $(this).css('top', top + 'px');
        $(this).css('position', 'absolute');
    });

    $('#item-queue .item .arrow').click(function()
    {
        if(animationInProgress == false)
        {
            var item = $(this).parent();
            var direction = ($(this).hasClass('up') ? 'up' : 'down');

            if(direction == 'up' && $(item).attr('data-order') > 1)
            {
                var swap = $('.item[data-order="' + (parseInt($(item).attr('data-order'), 10) - 1) + '"]');
                moveItem(item, swap, direction);
            }
            else if(direction == 'down' && $(item).attr('data-order') != $('#item-queue').children().length)
            {
                var swap = $('.item[data-order="' + (parseInt($(item).attr('data-order'), 10) + 1) + '"]');
                moveItem(item, swap, direction);
            }
        }
    });

    function moveItem(item, swap, direction)
    {
        animationInProgress = true;

        var itemTop = 0;
        var swapTop = 0;

        if(direction == 'up')
        {
            itemTop = parseInt($(item).css('top'), 10) - $(swap).outerHeight();
            swapTop = parseInt($(swap).css('top'), 10) + $(item).outerHeight();
        }
        else if(direction == 'down')
        {
            itemTop = parseInt($(item).css('top'), 10) + $(swap).outerHeight();
            swapTop = parseInt($(swap).css('top'), 10) - $(item).outerHeight();
        }

        $(item).animate({
            top: itemTop + 'px'
        }, 500, function()
        {
            animationSteps++;
            if(animationSteps == 2) resetAnimationValues();
        });

        $(swap).animate({
            top: swapTop + 'px'
        }, 500, function()
        {
            animationSteps++;
            if(animationSteps == 2) resetAnimationValues();
        });

        var swapValue = $(item).attr('data-order');

        $(item).attr('data-order', $(swap).attr('data-order'));
        $(swap).attr('data-order', swapValue);
    }

    function resetAnimationValues()
    {
        animationSteps = 0;
        animationInProgress = false;
    }
});

now...

All items are displayed normally on the page. Once the page has loaded each of the items in the queue are positioned absolutely (in relation to the relative queue element).

I am now using a custom attribute to record the order of the elements are on-screen as DOM order does not matter in absolutely positioned items.

Have a look at the latest code in action...

  • 0
  On 14/08/2011 at 20:55, Brian Miller said:

What does this line do?

$('#item-queue').css('height', $('#item-queue').height());

Sets the height of the item-queue element so that the content below it does not shift.

  • 0
  On 14/08/2011 at 21:06, Mathachew said:

Sets the height of the item-queue element so that the content below it does not shift.

Exactly, the height is initially set to 'auto' so once all the containing children are set to absolute (removed from the normal flow of the document) the actual height of the container will be reduced to 0.

Try it out yourself by removing that one line of javascript and putting extra content underneath the item-queue div.

  • 0
  On 14/08/2011 at 21:33, Brian Miller said:

Good stuff.

I was confused, thinking it was the equivalent to x=x, which seemed unneeded but your explanation makes sense.

The first part sets the height, while the second gets the height. Breaking it down looks like this:

var height = $('#item-queue').height();

$('#item-queue').css('height', height);

// alternate set method
$('#item-queue').height(height);

The result is the same in either case. There are several jQuery functions that operate as a getter/setter: height, width, html, text, and val immediately come to mind.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • 12TB Seagate IronWolf Pro CMR NAS HDD is at its lowest price by Fiza Ali The 12TB Seagate IronWolf Pro Internal hard disk drive is currently selling at its lowest price in over two years, so you may want to check it out in case you have been wanting to upgrade your storage solution. The IronWolf Pro is engineered for 24×7 operation in multi‑bay, multi‑user NAS and RAID environments. Utilising conventional magnetic recording (CMR) technology and a 7,200RPM spindle speed, it promises consistent, high‑throughput for long hours. The drive connects via a SATA 6Gb/s interface and supports unlimited drive bays. The IronWolf Pro's 256MB cache further enhances data transfer efficiency. Optimised for RAID arrays, it features Seagate’s AgileArray technology, dual‑plane balancing, and Time‑Limited Error Recovery (TLER), alongside built‑in rotational vibration (RV) sensors to ensure stable operation in multi‑drive setups. Moreover, with a workload rating of 550TB per year and a mean time between failures (MTBF) of 2.5 million hours, this drive is built to withstand demanding commercial and enterprise usage. The drive includes a five‑year limited warranty and three years of complimentary Rescue Data Recovery Services as well. Finally, IronWolf Health Management is integrated into compatible NAS systems to monitor drive health. 12TB Seagate IronWolf Pro HDD: $218.49 (Amazon US) 13% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. You can also check out other HDD deals here. For solid-state drives, you can head over to our SSD deals section to see if anything from there matches your requirements. Make sure you also browse through Amazon US, Amazon UK, and Newegg US to find some other great tech deals. As an Amazon Associate, we earn from qualifying purchases.
    • Thanks yeah, I have reached out on Lian Li Facebook. I'll use the contact form if I don't get helped there.
    • It's not about the amount of work. How can you not know that? Game companies charge what the market will bear, not based on what it cost to make. The market will clearly bear any price for a Mario series game because of the huge number fans across many decades. I don't expect Outer Worlds 2 to support that price point with matching huge sales numbers. I guess we'll know soon enough at release.
    • Windows 10 KB5060534, KB5060532, KB5060530, KB5060529 recovery updates released by Sayan Sen Microsoft this week released Patch Tuesday updates for the month of June 2025 on Windows 10 (KB5060533 / KB5060531 / KB5061010 / KB5060998) and Windows 11 (KB5060842, KB5060999). Alongside that dynamic updates for Windows 10 were also published. This time there were no such updates for Windows 11 which is quite rare. Dynamic updates bring improvements to the Windows Recovery in the form of Windows Recovery Environment (WinRE) updates, also called Safe OS updates, as well as to the Setup binaries in the form of Setup updates. These Dynamic Update packages are meant to be applied to existing Windows images prior to their deployment. These packages include fixes to Setup.exe binaries, SafeOS updates for Windows Recovery Environment, and more. Dynamic Updates also help preserve Language Pack (LP) and Features on Demand (FODs) content during the upgrade process. VBScript, for example, is currently an FOD on Windows 11 24H2. Only recovery updates were released. The changelogs are given below: KB5060534: Safe OS Dynamic Update for Windows 10: June 10, 2025 KB5060532: Safe OS Dynamic Update for Windows 10, version 21H2 and 22H2: June 10, 2025 KB5060530: Safe OS Dynamic Update for Windows 10, version 1809 and Windows Server 2019: June 10, 2025 KB5060529: Safe OS Dynamic Update for Windows 10, version 1607 and Windows Server 2016: June 10, 2025 Microsoft notes that the updates will be downloaded and installed automatically via the Windows Update channel. You can also avail them manually on Microsoft's Update Catalog website: KB5060534, KB5060532, KB5060530, and KB5060534.
    • Hello, I didn't see any replacements listed at https://lian-li.com/product-category/accessories/, but they do have a contact page at https://lian-li.com/contact-us/.  I suspect reaching out to them would produce further information about the availability of a replacement.  Regards, Aryeh Goretsky  
  • Recent Achievements

    • Apprentice
      Wireless wookie went up a rank
      Apprentice
    • Week One Done
      bukro earned a badge
      Week One Done
    • One Year In
      Wulle earned a badge
      One Year In
    • One Month Later
      Wulle earned a badge
      One Month Later
    • One Month Later
      Simmo3D earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      557
    2. 2
      ATLien_0
      256
    3. 3
      +FloatingFatMan
      178
    4. 4
      Michael Scrip
      123
    5. 5
      Steven P.
      97
  • Tell a friend

    Love Neowin? Tell a friend!