Henry Marshall
Henry Marshall

Reputation: 870

Link prepended to div with jQuery can't be used as selector for another bind

I am trying to implement a feature where you can pin elements from the main content area into a smaller div. This feature works as expected.

$('.pin').bind('click', function() {
  $('#sbStar').prepend($(this).parent().parent().parent('.leaf').clone(true));
});

EDIT: Changing clone() to clone(true), as per Vega's suggestion, fixed my earlier problem (below), but has not resolved it completely. Now I am trying to get the expand button to do a different behaviour depending on whether it is in #sbStar or is in the main content area. Unfortunately, this ('#sbStar .expand') still doesn't work.

$('#sbStar .expand').bind('click', function() {
  console.log('expand');
});

For Reference, the HTML:

<article class="leaf">
  <footer>
    <aside class="left">
      <a href="#" class="expand">E</a>
      <a href="#sbStar" class="pin">P</a>
    </aside>
  </footer>
</article>

Original Issue: $('.expand').bind('click', function() { console.log('expand'); });

Upvotes: 0

Views: 76

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You can do one of the following to fix your issue,

a. Use clone(true) - The true indicates whether event handlers and data should be copied along with the elements.

b. Bind the event handler function after the clone.

function myHanlder() {  console.log('expand'); }

.clone().bind('click', myHandler);

c. Use delegated events.

$('#sbStar').on ('click', '.expand', function () { ... });

Upvotes: 2

Related Questions