tags:

views:

63

answers:

3

This is my first day of jQuery, so bare with me. Currently, I am adding an element to my parent container by doing the following:

var uploadedContainer =$('#uploadedimages');
var uploadedItem = '<div><span>'+file.name+'</span><span><a class="mylink" href=remove.aspx?img='+safeUrl+'>Remove</a></span></div>';
uploadedContainer.append(uploadedItem);

While it works, I'm not sure if that's the right way to accomplish this task. Also, is it possible to add the element to the parent, and fade the child element in? An example of usage would be great!

Thanks! George

+5  A: 

As for needing to create a complicated element over and over, I would prefer cloning a dom-element as opposed to working with a long and complicated string. Place this somewhere in your html:

<div class="template" style="display:none;">
  <span class="file_name"></span>
  <span class="file_link">
    <a class="mylink" href="#">Remove</a>
  </span>
</div>

Now any time you need to clone that:

$( $(".template").clone() )
  .find("span.file_name").html(filename).end()
  .find("span.file_link a").attr("href", safeUrl).end()
  .removeClass("template")
  .appendTo(uploadedContainer)
  .hide()
  .fadeIn("slow");

Demo Online: http://jsbin.com/ucayi/2/edit

Jonathan Sampson
+1  A: 

That code should work. You can add this code to fade something in:

  $('#uploadedimages').fadeIn('slow', function() {
    // Animation complete
  });

You'll need to set the visibility of uploadedimages to hidden for this to work.

The JQuery documentation is very good. I would suggest visiting the JQuery site.

Here is a link for you regarding fading something in.

mdm20
A: 
var uploadedItem = '<div><span>'+file.name+'</span><span><a class="mylink" href=remove.aspx?img='+safeUrl+'>Remove</a></span></div>';

You should avoid slinging HTML together with strings like this. What if file.name or safeUrl has a < or & character in? In the best case you're generating invalid HTML, in the worst case you've just left a cross-site-scripting security hole in your app.

Also, there is no encodeURIComponent encoding on safeUrl (unless you've done that already). That would need to be done too for reliability. There are also many more characters that might break with safeUrl due to the missing quotes on the href attribute.

Better: use the text() method to set the text content of an element, and attr() to set an attribute to a value. Then you do not need to worry about HTML-escaping. eg.:

var div= $('<div><span></span><span><a class="mylink">Remove</a></div>');
div.find('span').eq(0).text(file.name);
div.find('span').eq(1).attr('href', 'remove.aspx?img='+encodeURIComponent(url));
div.appendTo('#uploadedimages');
bobince