tags:

views:

21

answers:

1

I am using .prepend() and .remove() to show menu items in the order a user clicks them.

$(document).ready(function()
{
    $('#item1').click(function() 
    {

        $('#item1_content').remove();

        $('.menu_item_content').prepend('<div id="item1_content">The Box For Menu Item One</div>');

    });

    $('#item2').click(function() 
    {

        $('#item2_content').remove();

        $('.menu_item_content').prepend('<div id="item2_content">The Box For Menu Item Two</div>');

    });
});

I use .remove() to remove the item if it already exists and the .prepend() to put it at the top of the container div

In this way the user can show as many or as few of the menu items as they want at once and in the order they click them but duplicates should not appear.

For example. The user could click MenuItem3 then MenuItem1 Then MenuItem2 and the items would display below:

Item2 Item1 Item3

The first half of my script works #item1 but #item2 does not, it just keeps making duplicates.

Also if I do #item1 then #item2 then #item1 again I get a duplicate.

What am I doing wrong here? Is there a better way to do this?

A: 

You actually don't need the remove() function at all. This should work nicely, assuming that your HTML is similar:

<div class="menu_item_content">
  <div id="item1">
    <div id="item1_content">MenuItem1</div>
  </div>
  <div id="item2">
    <div id="item2_content">MenuItem2</div>
  </div>
  <div id="item3">
    <div id="item3_content">MenuItem3</div>
  </div>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script>
jQuery(document).ready(function() {
  jQuery('.menu_item_content').children().click(function() {
    jQuery('.menu_item_content').prepend(jQuery(this));
  });
});
</script>
Mark Eirich
Will this work if I want to show just a variable number of menu items? For example if the user only clicks 1 i only want 1 to show.
ian
@ian: Could you edit your question to include the relevant part of the HTML? It is difficult to see exactly what you're attempting to do.
Mark Eirich
@ian: I ran your code with `<div id="item1">Item 1</div><div id="item2">Item 2</div><div class="menu_item_content"></div>` as the HTML and it works perfectly fine. Have you tried using FireBug or some other Javascript console to see if you're getting some error message? All I can think of is that your HTML is incorrect or you are using an old version of jQuery.
Mark Eirich