Reputation: 53
I am working with a bit of software which uses Smarty block templates, to 'include' another template it is as simple as;
{include file='frontend/folder/file.tpl'}
However, then anything I try to use jQuery on get's completely ignored, like it's not adding it to the DOM, example:
<label id="testonetwothree">test</label>
and then in the js file (yes jQuery is included)
$('#testonetwothree').click(function(e){console.log('test);});
When you click the label, nothing happens, which tells me it's not added to the DOM so it cannot find it, however, when I check where the event came from using:
$( "body" ).click(function( event ) {
console.log("ID: " + event.target.id );
}
The element 'testonetwothree' clearly gets clicked, so I can in fact do;
$( "body" ).click(function( event ) {
if(event.target.id == "testonetwothree"){
console.log('clicked testonetwothree');
}
});
But that's hardly a solution, I feel like I am just not adding to the DOM correctly or I am going wrong somewhere, if anyone who has experience with Smarty can help, I will appreciate it greatly.
Upvotes: 0
Views: 89
Reputation: 3790
As i mentioned in comments, you can use the dynamic element binding with .on()
Example:
$('body').on('click', '#testonetwothree', function(){ console.log('testity');});
Now, on the matter of event.target.id == "testonetwothree"
vs $('body').on('click', '#testonetwothree
.
Those are not equivalents, first of those will compare only the top level child that was clicked, while the latter will bubble events.
Example:
<div id="clickone">ONE<div id="clicktwo">TWO</div></div>
Assume this is your html, with the way you are comparing, when you click on "clicktwo" you won't proc the "clickone" onclick. Now with .on()
the event will be run.
Lastly, since you mentioned that you feel like it isn't the "right" way:
This is perfectly fine way of attaching events. When you check jquery docs for the .click()
event you can find out that: "This method is a shortcut for .on( "click", handler ) " and in fact the .on()
version is the one that has more features (like dynamic elem binding :))
Upvotes: 1