user2304993 user2304993 - 6 months ago 14
jQuery Question

DIV inside of DIV appendTo with .data

What I am trying to achieve:

I am trying to apply a div with a div inside, to a specific element on my page, with appendTo and then make it draggable. Applying a sole dive with appendTo and making it draggable works fine. What I cannot figure out is how to put a div inside of the div that I use appendTo on.

I will post the script that works first and then the one that does not, with the extra div inside.

Script that works:

$('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle').appendTo($("#" + id).parent()).draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
}).hide().fadeIn(2000);


Script that does NOT work:

$('<div>' + ('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtext text-justify') + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle').appendTo($("#" + id).parent()).draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
}).hide().fadeIn(2000);


Thanks

I am quite sure that my syntax is incorrect or that I am simply using the wrong kind of mechanic to do what I want to do. I would appreciate any kind of help, tips or other such. Thanks very much in advance.

Answer

What you are trying to do is to combine jQuery object and HTML string and functions, which is the problem.

The first rule is to try to format the code in a way it makes sense to you. Then it will be very easy to figure out where exactly it went wrong.

Lets try to break down your code.

This part

$('<div>' + ('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtext text-justify') + '</div>')

should be like this

$('<div>')
  .append(
    $('<div>' + rText[i] + '</div>')
      .data('number', next[i])
      .attr('id', +next[i])
      .attr('class', 'rtext text-justify')
  )

Complete code

$('<div>')
  .append(
    $('<div>' + rText[i] + '</div>')
      .data('number', next[i])
      .attr('id', +next[i])
      .attr('class', 'rtext text-justify')
  )
  .data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle')
  .appendTo($("#" + id).parent())
  .draggable({
    containment: '.site-wrapper',
    stack: '#testpile div',
    cursor: 'move',
    revert: true
  }).hide().fadeIn(2000);
Comments