-4

I am trying to call a function from a dynamically generated button. However the click() function is not working when I click the link. Can't figure out why.

if ( hasCap === 'image' ) {
  caption = $(this).data('caption');
  link    = '<a href="#" style="float: right; margin-top: -10px;" class="hidecaption">Hide Caption</a>';

  return link + (caption ? caption + '<br />' : '') ;
}

  $( ".hidecaption" ).click(function() {
      alert( "target called" );
    });
kig
  • 163
  • 1
  • 9
  • You need yo select parent and add click for children like $(parent).on(click,child,function(){}); – sTx May 19 '17 at 17:14
  • Events are not bound to elements created dinamically. What you need is an element that exists in the DOM when the page loads. This existing element will act as an "anchor" from where the event will be bound. The DOM element you choose to use, has to be a parent of your dynamic element. For more info check [JQuery on() method](http://api.jquery.com/on/) – Omar Yafer May 19 '17 at 17:24

2 Answers2

0

Does your jQuery function inside the function following?

$(document).ready(function{}); 

jQuery click event will fired after document load.

黃冠融
  • 21
  • 3
0

You need to something along the lines of

$("EXISTING_DOM_ELEMENT_SELECTOR").on(
     "the_event", 
     "dinamic_element_selector", 
      function yourBehaviour(){
         //The code of your function goes here
      }
);

In your case you would have

$(".existing-parent").on('click', '.hidecaption', myBehaviour)
function myBehaviour(){}

This would translate roughly to: For any element with the class .hidecaption inside .existing-parent, add an click event listener that will execute the function myBehaviour(). myBehaviour is separated in another function only for readability´s sake.

The .existingParent serves as something similar to an achor for your dynamic elements.

Omar Yafer
  • 823
  • 6
  • 17