I am having some problems getting this part of my jQuery script to run after the Ajax – content switch...
/*no right click on img*/
$('img').bind('contextmenu', function(e) {
return false;
/*rollover*/
$('.roll').on('mouseenter mouseout', function() {
var original = $(this).attr('src');
var replacement = $(this).data('hoverimg');
$(this).attr('src', replacement).data('hoverimg', original);
});
});
Could someone please help me get it running I tried it whit a lot of Ideas, like:
var init = function(){
/*Code*/
}
Or
function init(){
/*Code*/
}
I am a bit confused right now.
2 Answers 2
There's one point that you make sure that if you are binding event on to the element that is dynamic then you should reference it through some static data which is already on the page like body or document. Example :
$('body').bind('contextmenu','img', function(e) {
return false;
/*rollover*/
$('body').on('mouseenter mouseout','.roll', function() {
var original = $(this).attr('src');
var replacement = $(this).data('hoverimg');
$(this).attr('src', replacement).data('hoverimg', original);
});
});
Try running it now. It will definitely work.
1 Comment
If I understand correctly, you need to bind this only on ajax success. Then you can try binding and unbinding in jQuery.
unbind before calling the ajax and bind it back in the success callback of ajax.
However I would prefer to use .on() and .off() event handler attachments.
See this SO answer for .on VS .live VS .bind
.rollinside the contextmenu handler but after thereturn false, so that.on()statement will never run. If that's just because you've only put some of your code in the question please show a more complete sample. And please describe clearly what the desired effect is.AJAXsuccess??http://api.jquery.com/live/to see whether you can do your stuff after the call on DOM elements ..live()was removed from jQuery in v1.9? Use the delegated form of.on()instead (assuming a delegated handler is appropriate here, which is hard to tell from the limited description in the question).