I have a view, that is refreshed with ajax. I'm using Jquery 1.7.2
You click a button, that call a javascript function :
$(view_identifier).trigger('RefreshView');
Before this refresh, I've attached on click handler to an ajax link. The link call a modal popup and must trigger a javascript function. The link contains a picture, but I have tested with just text and I get the same result. So I'm trying to attach an handler to an ajax link.
Here is the html :
<body>
//lot of things ....
<a class="use-ajax">
<img width="25" height="25" src="/sites/default/files/picture.png">
</a>
//lot of things
</body>
And here is the javascript :
$('a.use-ajax > img').on('click',function(){
console.log('test');
foo();
});
That work fine, until the view is refreshed. After the refresh, the function foo isn't being called anymore. Thats because the handler is not being attached to dynamic elements.
So I change the part above to this :
$(document).on('click','img',function(){
console.log('test');
foo();
});
So that I can use the event delegation provide by Jquery.
And it isn't working. When I click on the link, nothing is happening. The strange part is when I remove the use-ajax on the link (become a normal link without the Drupal ajax part), it works.
I've tested a lot of variation and nothing seems to work.
I've used an old jquery code :
$(document).click(function(event){
//check if its a click on the link with event
console.log('test');
})
and It doesn't trigger either. If I click anywhere on the page, the 'test' show up in console, but not when I click an ajax link. I don't understand this because, it would mean that the link isn't in the dom.
Does anyone have an idea ?
.use-ajax
elements either returnsfalse
, or does a nice littlee.stopPropagation()
, shorting out your code$.on
works because of event bubbling, so when you click on a link all its parents receive the click too, with the order going from deepest (i.e. the link itself), out to the shallowest (document). If the link has an explicit event handler which stops propagation, or if any other element up the chain does the same thing, the event will simply never bubble up to thedocument
, which your event handler is attached to, so the code will never run$('body').on('click', 'a.use-ajax', function(e){ alert('test'); });
, the number of event does not change when I run thisconsole.log($("a.use-ajax").first().data('events'));
. It always print 1. The on function fails to attach the handler.