I have some javascript applying changes to some elements and a function loading more of such elements.
Like that:
<ol id="test"><li>click</li></ol>
<script type="text/javascript">
$(function() {
$('OL').delegate("li","click",function(){
$('#test').append('<li>click</li>');
});
</script>
This is the basic functionality of delegate and it works. I can click on multiple <li> elements.
The problem is that i want to, additonaly do the following:
$(function() {
$('li').css('color','red');
//this is just an example, I don't need to paint the text red :)
});
for all li not just the ones that are loaded at the page load.
I haven’t been able to attach those changes to anything (there is no event that indicates that I have loaded the elements in the append above).
Also I know I could recall $('li').css('color','red'); every time I call the append (or on ajax callbacks which are the thing I’m really working). But I have a system with a lot of ajax calls that return different HTMLs and a lot of pluggins and jquery staff that needs to be executed against this elements. I don’t want to do a giant “refresh” function to be called on every ajax success.
Right now the only solution I find is to bind everything to an arbitrary event and do a trigger call for that event on every ajax load like that:
<ol id="test"><li>click</li></ol>
<script type="text/javascript">
$(function() {
$('OL').delegate("li","click",function(){
$('#test').append('<li>click</li>');
$('#test').children().trigger('load');
});
</script>
<script type="text/javascript">
$(function() {
$('OL').delegate("li","load",function(){
$(this).css('color','red');
});
});
</script>
This works for all elements loaded afer the first. So I would need some extra code but it works.
Does anybody have any better solution?
Any way to do a “live” for non events?
Thanks!
EDIT
Regarding the “red” example in the code… the changes I need to do are those amongst many others:
('BODY').delegate(".mcs_container","load",function(){
$(this).mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","no","no",0);
}).trigger('load');
So I think only triggering a function will work.
EDIT 2
I’ve created a working example here:
http://jsfiddle.net/THHNS/5/
What I’m trying to accomplish is to be able to avoid the extra trigger $('LI').trigger('focus');
EDIT 3
I was using delegate when ON should be enough and better.
The updated example:
http://jsfiddle.net/THHNS/26/
Well, it seems that is not possible to atach live function calls to something that is not an event.
The best solution I’ve find that works is the following.
You can try it here.
http://jsfiddle.net/THHNS/33/
@charlietfl suggested that one could chain the trigger in (note 2) chained to the declaration in (note 1) but I haven’t been able to make it work.
I’m sure it can be done with less lines anyway. But I guess this solution will suffice to keep my code organized in the one page full ajax loads project I’m working.
Thanks to all!