tags:

views:

51

answers:

3

So what I'm trying to accomplish is a simple appendTo a certain element. The issue I'm having is after execute is run, it appends to the location but then proceed to go back to the ul it resides in.

<script type="text/javascript">
    function execute() {
      $('#desCopy').appendTo('#description')
      $('#imgPlace').appendTo('#IMGbox')
    }
</script>

<div id="content" style="background:#000; width:989px;">
    <div style="float:left; left:18px; margin:0; width:337px; position:relative; padding:15px 0 0 0; color:#FFF;">
        <div id="description">
        </div>
    </div>

    <div
      id="IMGbox"
      style="float:left; position:relative; display:block; background:#F00; width:652px; height:258px; background:#0FF; overflow:hidden;">
    </div>

    <div style="float:right; background:#CCC; height:25px; width:652px;">
        <ul>
            <li><a href="" onclick="execute()">Slide 1</a>
                <ul style="">
                    <li><span id="desCopy">Test description, Test description</span></li>
                    <li><img src="images/test.jpg" id="imgPlace"></li>
                </ul>
            </li>
        </ul>
    </div>
</div>
A: 

You have to return false from execute to prevent event bubbling.

luca
In this case the issue is not with bubbling, but rather with the default behavior of the `a` element being clicked.
patrick dw
+1  A: 

Change the event handler setup like this:

<a href="" onclick="execute(); return false">

Better yet, set it up with jQuery and have the handler return false:

// somewhere in your initialization code:
$(function() {
  $('#theAnchorTag').click(function() {
    $('#desCopy').appendTo('#description');
    $('#imgPlace').appendTo('#IMGbox');
    return false;
  });
});

You'd have to give your <a> an "id" value ("theAnchorTag" in my example), or you could identify it some other way in the selector where the "click" handler is set up. You're really better off using jQuery to bind event handlers; those "onfoo" attributes are pretty icky.

Pointy
+1 Deleted my answer. Thanks for pointing out the error. May not be a bad idea to give Starboy a full jQuery solution.
patrick dw
thanks dude - it's really hard for me to type fast enough to beat you to an answer :-)
Pointy
Thanks for the response Pointy!
Starboy
A: 

The problem is that an empty href (as is the case with your link) will reload the page when clicked..

So you rearrange your li elements and then the page gets reloaded reverting everything back to how they originally were..

As mentioned in the other answers you need to cancel the default click action by returning false from your handler..

You should also look to assigning the handler with jquery instead of inline attributes..

Gaby
Thanks for the explanation here Gaby, really does help me out.
Starboy