2

I am trying to use <template></template> tags in my HTML to hold content that can then be displayed in the page. I am currently grabbing the template contents using html() and writing them to the div using html(). This all works as expected, but when the content is displayed in the div, things like button click events are not triggering. So the content seems to be out of scope. I assume this may be because it was loaded using html(). Is there a better method I can use or is the problem caused by something else?

Example code

window.launcher = function(){
    $('#launch').on('click', function(){
        var content = $('#content').html();
        $('#container').html(content);
    });
};

window.launcher2 = function(){
    $('#launch2').on('click', function(){
        alert('You clicked me!');
    });
};

The second function will not fire.

Fiddle

Edit: fixed typo

Ally
  • 947
  • 1
  • 13
  • 30
  • 1
    Use [event delegation](http://learn.jquery.com/events/event-delegation/) `$('#container').on('click', '#launch2', function () {` Check https://jsfiddle.net/tusharj/bch0ym09/1/ – Tushar Sep 26 '15 at 16:07
  • there is a `u`missing in your code und in the fiddle near `$('la(u)nch2')`. – radscheit Sep 26 '15 at 16:12
  • @Tushar, but what if the clickable element could be anything, such as link, button, text etc? – Ally Sep 26 '15 at 16:28
  • @radscheit I have fixed the typo thanks – Ally Sep 26 '15 at 16:29
  • @Ally Yes, the above approach will work no matter what the element is, as you're adding the element dynamically I've suggested event delegation – Tushar Sep 26 '15 at 16:31
  • Thank you @Tushar. That's 2 things you have taught me in one day :) I have used `$('body').on('click', '.element'....` as this code can be used anywhere on page, and it now works. – Ally Sep 26 '15 at 16:42

1 Answers1

0

You have to put your jQuery action inside action where your objecty ex. launch2 exists. You code didnt wroked because you tried to grab elemnt in place where that element did not existed.

Working exampe below:

$('#launch').on('click', function(){
        var content = $('#content').html();
        $('#container').html(content);
            $('#launch2').on('click', function(){
                alert('You clicked me!');
            });
    });

also u have type in here:

$('#lanch2') it should be $('#launch2')
fsn
  • 549
  • 3
  • 11
  • 1
    Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected. – peterh Sep 26 '15 at 17:22