Reputation: 1996
I have a block in my sidebar. When resizing below a certain size, I put it in my main content. When I resize back up to the original size, I want it to go back where it came from. Problem is, this block is in different spots in the sidebar on different pages. It's always just one, so it has an ID, but sometimes it's the first sidebar item, sometimes it's the second.
How do I put this thing back where it started when I resize the page larger again?
For example, when my page is smaller than 640px wide, block #foo is moved with jQuery to below element #bar.
$("#bar").after($("#foo"));
All is well. But when I resize back to a size larger than 640px wide, everything pops back into place except #foo
, obviously. I could just pick a spot in the sidebar and always put it back there regardless of where it came from in the sidebar, but that's no fun.
I know it's possible to use things like #baz :eq(n)
to find the nth item within #baz
... is there a method like $("#baz").getOrdinalPosition($(".parent-of-baz"));
to find the location of #baz
within its parent element before I move it, so I know where to put it back?
Upvotes: 0
Views: 89
Reputation:
You can use an HTML5 data attribute to hold the order of the sidebar blocks, then you'll know where to put it back:
<div id="foo_block" data-sidebar-pos="1">Content</div>
<div id="bar_block" data-sidebar-pos="2">More Content</div>
<div id="other_block" data-sidebar-pos="3">Other Content</div>
Then if bar_block
gets moved inside the main content, it will retain its position data. Putting it back is just a matter of inserting it after the block with the next lowest sidebar position, or if the position is 1, insert it at the top.
Upvotes: 1
Reputation: 693
You could just use a wrapper <div>
and put it back inside the wrapper to regain its former position, but I'm not too keen on moving of elements inside the DOM. That is normally not the right way to do things. It would probably be better to have two instances of the block and toggle them with display:none/block
.
Upvotes: 2