Gary Ryan
Gary Ryan

Reputation: 754

Appending and manipulating elements

Please see the my test site here.

The script is written in the <head> so you will be able to see it there.

Instructions

If you click the blue area a new element will be made. Do this four or five times. Now click all the elements you've just created. They should all have a black outline. However, some do and some don't.

Additional Info:

Only tested on chrome so far.

Any ideas on what's going wrong here?

Upvotes: 0

Views: 64

Answers (2)

Nathan Loyer
Nathan Loyer

Reputation: 1349

You can simplify using this:

$(function () {
  // CREATE A NEW BUBBLE

  $('.drop').click(function(event){
    Bubble(event);
  });

  var newBubbleId = 0;
  function Bubble(event,bubbleClass){
    // Create Element
    var id = newBubbleId++;
    var bubble = $('<div class="bubble" id="b_'+id+'" draggable="true"><input id="bubbleText" type="text" name="text" value="'+id+'" /></div>');
    $('body').append(bubble);

    // Position Element
    var bubbleWidth = bubble.width();
    var bubbleHeight = bubble.height();
    var x = event.pageX - (bubbleWidth*0.5);
    var y = event.pageY - (bubbleHeight*0.5);
    bubble.offset({top:y, left:x});
    bubble.click(function () {
      $(this).toggleClass("active");
    });
  }

});

I see a few other issues. Number ids as mentioned before. Also, all your input elements have the same ID, that is not allowed. One ID per document only. You can use the Name attribute if you want them to have the same name.

Also, your counter function isn't ideal.

But this should solve your problem.

Upvotes: 1

katspaugh
katspaugh

Reputation: 17939

You are adding the click listener to all bubbles each time a new one is created.

Add the listener once with the live listener. It can be set before any of the bubbles are created.

And don't use numeric id attributes, it's disallowed by HTML.

Also, you are toggling the active class -- there's a shorter function for this -- toggleClass.

Upvotes: 1

Related Questions