Wednesday, 19 February 2014

How to change the order of div (DOM element) using jquery 6

Thank you for asking me this question, Vicky. I'm going to explain the way I solved your issue here...

Question :

i want from this fiddle is if the user clicks button 3 then button 1 then button 5 ..... the divs should display in this order DIV 3 > DIV 1 > DIV 5 , But its displaying as DIV 1>DIV 3>DIV5

Answer :

To achieve this task we need detach() method of jQuery. I have already posted about this detach() method in one of previous my another article. You can find it here.

When i tried to solve this issue i searched in web, most of them tried to solve it using javascript array and created those div's dynamically from javascript during click event of buttons.

But, we can solve it in a much simple way using jQuery's detach() method.

The fiddle which is given in the question section is totally hard coded.

   $("#but1").click(function () {  
     $("#f1").show();  
   });  
   $("#but2").click(function () {  
     $("#f2").show();  
   });  
   $("#but3").click(function () {  
     $("#f3").show();  
   });  
   $("#but4").click(function () {  
     $("#f4").show();  
   });  
   $("#but5").click(function () {  
     $("#f5").show();  
   });  

Previously those div's are hidden using css display : none property.

So, I assigned btn css class for those buttons in html part and then I changed that code like the one given below.

   $('.btn').click(function () {  
     var clicked = $(this).attr('id');  
     var clicked_id = clicked.substr(clicked.length - 1);  
     $('#f' + clicked_id).detach().appendTo('#filterpanel').show();  
   });  

You can now see, how I used jQuery's detach() method to detach the element from the DOM tree and append it to #filterpanel div. By this method, the detached DOM element will insert it as a last child of #filterpanel div.

Here you can fine the resultant fiddle DEMO.

6 comments:

  1. Good demonstration... Keep it up :)

    ReplyDelete
  2. very useful one ...... and a straight forward method to do the same .... keep it up bro ... :))

    ReplyDelete
  3. Awesome post! Demo explanation concept will help us to understand easily.

    ReplyDelete
  4. Thanks to placed your golden words in this comment box for this post...

    ReplyDelete