views:

10

answers:

1

Dear Experts,

I wanted to achieve an effect to switch the position of the 2 HTML Divisions when they are clicked.

So when clicked, the top will shift to the bottom and bottom will shift to the top.

Here is what I can come up with

<html>
<head>
  <script type="text/javascript">
$(document).ready(
    function(){
        $('div').click(
            function(){
                $(this).insertBefore($(this).next());
            }
        );
        }
        )
  </script>

  <style type="text/css">
  body{
    margin: 0;
   }
    #top{
height: 100px; 
width: 100px;
background: rgb(206,206,203);
    }

    #bottom{
        height: 100px;
        width: 100px; 
background: rgb(226,206,203);
     }
  </style>

</head>
<body>
        <div id="top"></div>
        <div id="bottom"></div>
</body>
</html>

I know there is a way to select the specific Element using class in the Jquery selector as follows

  <script type="text/javascript">
$(document).ready(
    function(){
        $('div').click(
            function(){
                **$('#bottom').insertBefore('#top');**
            }
        );
        }
        )
  </script>

But I just wanted an generic way to shift elements with arbitrary names and class names.

Thanks in advance.

+1  A: 

I'd suggest using a unique class to associate each pair, then you can do something like:

$('.pair').click( function() {
    $('.pair:first').insertAfter( $('.pair:not(:first)') );
});
tvanfosson
thanks sir,but BUG
Dennis D
nvm fixed thank you
Dennis D
I have another question. How can this permanently affect the layout of the Dom? Can this switch be saved permanently on the markup?
Dennis D
@webzide -- you'd have to send back the change to the server via AJAX and have the server-side understand how to generate the page based on some persistent knowledge of the ordering of the divs for that particular user. That is you store the order in a database, associated with the user. When you generate the page, you generate the divs in the user's preferred order. In the click handler you pass back to a server action, the new order and it saves it in the database so that the next time the page is generated, it's generated in the new order.
tvanfosson
Thank you.God bless you.
Dennis D