0

I have the following JQuery code:

jQuery(document).ready(function($) {
        var retrievedList = [ {
            "id" : "one",
            "content" : "toto"
        }, {
            "id" : "two",
            "content" : "titi"
        }, {
            "id" : "three",
            "content" : "tutu"
        } ];
        $("#clickMe").click(function(evt){
            $.each(retrievedList, function(i, v) {
                if(!$('div#list> span#' + v.id).length) {
                    $('<span />').prop('id', v.id).text(v.content).appendTo('#list').show(8000);
                }
            });
            return false;
        });
    });

I am surprised to notice that the show function call does not work on the span that I create.

Can anyone tell me why and how to remedy this problem?

EDIT: Here is the html:

<div id="list">
<span id="one">toto</span> <span id="two">titi</span>
</div>
<a href="" id="clickMe">clickMe</a>
balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

1

Instead of this:

$('<span />').prop('id', v.id).text(v.content).appendTo('#list').show(8000);

Try using this:

var span = $('<span />').prop('id', v.id).text(v.content).css('display', 'none');
$('#list').append(span);
$('#'+v.id).show(8000);
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • Have you checked to see if the `span` is actually appended? – Bogdan Sep 20 '12 at 11:47
  • I've updated the answer. If the `span` is indeed appended, using an id selector should work – Bogdan Sep 20 '12 at 11:51
  • 1
    Updated the answer again. The `span` needs to be hidden for the show effect to work. You can do it with `hide` or with css `display: none`. – Bogdan Sep 20 '12 at 11:58
  • Thanks Spider. It's a bit of a hack but it does work. Funny we have to hide it in order to show it afterwards... – balteo Sep 20 '12 at 11:59
  • Actually that's how it should work. If the element was already visible when the `show` method was called then it would flicker because the `show method would need to hide it before it can animate it. – Bogdan Sep 20 '12 at 12:02
  • I tried with `display: none` as follows: `var span = $('').prop('id', v.id).text(v.content).css("display: none"); $('#list').append(span); $('#'+v.id).show(8000);` and it does not work. – balteo Sep 20 '12 at 12:02
  • 1
    It should be `css('display', 'none')`. See updated answer. http://api.jquery.com/css/ – Bogdan Sep 20 '12 at 12:05
  • With `display: none` I was reffering to add this rule to a css stylesheet like so `#list span { display: none; }` – Bogdan Sep 20 '12 at 12:06