• 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

    • What annoys me is the people that try to buy a higher end product, and then low ball you, and say but I don't need that function, all I need is to use it for video out so I don't feel like paying higher price.   I had a person that was trying to buy RTX 3080 from me for $100 and his excuse was, well I won't be playing games on it, I just need four monitor outout. Or someone was trying to buy 2TB Gen5 M.2 for $50, well I don't need the speed, is just for basic storage. Or i was offered $80 for 20TB hard drive, that person said well, right now I only about 7TB, so rest won't be in use Just some examples in last month or two...   The guy with the 3080, I replied to with something like go to Chevy dealer and offer them $15K for that brand new corvette and tell them that you you only need to drive to work, so you don't need to go fast.   There a lot of low ballers that try to take advantage.
    • Not in Syracuse, NY. They're about to break ground! https://www.syracuse.com/micro...on-and-other-tech-jobs.html
    • Here in Finland we have lots of rural areas with narrow roads, one of the highest taxes in the world (cars are taxed way above EU standards) and fuel is quite expensive. Yet we educate our drivers to drive responsibly and safely in all areas, and our people respect each others rights and freedom to move around safely. Which is why we have even small children under 10 years old walking and cycling alone to schools in the streets, even in big cities. Safety is about being responsible and about respecting others. And I would hate to see AI (or anyone else) destroy our way of life. There are and always will be outliers, accidents happen and machines break. I dont't want to see people relying on AI to do things like driving for them. I want people to think and react to the world around them themselves, and being responsible instead of them browsing TikTok or whatever instead of looking out the window, and then saying that "It wasn't me, it was the car". Already people walk around town with their eyes glued to a screen – I don't want people driving around the same way.
    • And I should hope none will. I don't want to walk ouside to have some randome AI drive over me and mine. Not that I want a person to do it either but I want there to be an actual person who takes responsibility of their actions instead of relinquishing control to a machine. In some highways I can accept self-driving, but even then there should be some kind of dead man switch etc. that actually monitors the drivers status.
    • No thank you. I want to drive myself, and not just because I don't trust a machine or whatever – I like driving, and I like doing it with a manual car without lane guidance and all other "driver assists". I wven rarely use cruise control. I went through and paid for to have a license to that allows me to do it, and do it responsibly instead of relinquishing control to a machine. I currently drive a van for work in a city, something like 200 km/day. If we everything is automated and computers decide everything for us, the dumber people will get since they don't have to bother thinking for themselves nor do they have to take responsibility for themselves since "it wasn't me, it was the machine" will be their future defence for everything. Soon, Neowin's writers will be out of a job because AI can do it just fine and it doesn't need pay. Wikipedia – a free service with voluntary writers – just started replacing real people with AI, and had to shut it down (at least for now). Lets let ai AI and those that run it (or rather run them) the keys the the world and watch it burn because no one is able to actually do anything without some AI assistant telling them what to do (driving included). What a world!
  • Recent Achievements

    • One Month Later
      POR2GAL4EVER earned a badge
      One Month Later
    • One Year In
      Orpheus13 earned a badge
      One Year In
    • One Month Later
      Orpheus13 earned a badge
      One Month Later
    • Week One Done
      Orpheus13 earned a badge
      Week One Done
    • Week One Done
      serfegyed earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      536
    2. 2
      ATLien_0
      247
    3. 3
      +FloatingFatMan
      176
    4. 4
      +Edouard
      166
    5. 5
      Xenon
      118
  • Tell a friend

    Love Neowin? Tell a friend!