Event call multiple time after ajax replace element - javascript

I have an problem with Jquery event. Jquery Event was call multiple time after I replace that element with another element but same type and same id.
// 1. ajax call success and replace my block
// 2. This is my event that I want it happen.
$(document).on("click", ".polaroid button.addImage", function(event) {
event.preventDefault();
// trigger browse file to upload
$(event.target).closest("div.polaroid").find("input[type=file]").trigger("click");
});
This code was used to resold event was call after AJAX success. So, why is button.addImage with event click called many times at the same time AJAX is called?
This is html:
<div class="col-md-3 polaroid">
<img src="images/ingredient/default_img.png" title="Main image" />
<input type="file" name="file-image" style="display:none"/>
<button type="button" data-toggle="tooltip" title="Add" class="btn addImage"><i class="glyphicon glyphicon-plus icon-plus"></i></button>
</div>

You most likely are loading this script again or calling a function that adds this event handler again
The best fix is to find where this event handler is being called again.
A workaround would be to namespace the event and always remove the event handler using off() before adding it again
$(document)
.off('click.polaroid')
.on("click.polaroid", ".polaroid button.addImage", function(event) {
// other code
});

use one()
$(document).one("click", ".polaroid button.addImage", function(event) {

Thanks. I found answer. that is use "off" before "on", like this:
I update the answer of Mr.charlietfl.
$(document)
.off('click',".polaroid button.addImage")
.on("click", ".polaroid button.addImage", function(event) {
event.PreventDefault();
// other code
});

Related

Why does document.off disable click on button started with document.on but not id.click in Jquery?

Why does document.off switches off click of buttons called using document.on but not $(id).click?
Following is code in which second button is not working:
<button type="button" id="rara">1</button>
<button type="button" id="baba">2</button>
<button type="button" id="hadimba">3</button>
$("#hadimba").click(function(e) {
alert('3')
});
$(document).on('click', '#baba', function(e) {
alert('2')
});
$(document).off('click').on('click', '#rara', function(e) {
alert('1')
});
JsFIddle
Could anyone please explain this phenomenon? why specific #id.click hit when whole document's event handlers are off?
The answer is simply scoping.
$(document) and $('#hadimba') are different objects, and both have their own event handlers. Removing an event handler from one, does not remove it from the other because they are two different objects.
Another way to look at it is that when you attach a click listener on $(document), you are telling $(document) what to do when it receives a click event. Likewise, when you add a listener to $('#hadimba') you are telling $('#hadimba') to do something when it receives a click event.
So when you remove that listener from $(document), it doesn't do anything when it receives the click event. However, this does not stop $('#hadimba') from doing something when it receives a click event.
You are not specifying any handler function for $(document).off('click').
But with immediate chaining with .on('click',... you are actually enabling click event agin.
Thus your off() should be:
$(document).off('click','#rara', function(e) {
alert('1')
});
For the second button you need to target document.body instead of just document.
$("#hadimba").click(function(e) {
alert('3')
});
$(document.body).on('click', '#baba', function(e) {
alert('2')
});
$(document).off('click','#rara', function(e) {
alert('1')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="rara">1</button>
<button type="button" id="baba">2</button>
<button type="button" id="hadimba">3</button>

Javascript function after html appended

I have a problem with my javascript function :
$(".like-btn").click(function () { .. }
this function is not triggered anymore after in my javascript somewhere else I do stuff like
$("#1021").append("'<button type="submit" class="btn btn-default like-btn" ... .etc ");
So basically I need my jquery to be triggered also after I add some more html on my page.
Since the like-btn class is added dynamically, you need to use event delegation to register the event handler like this:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#1021').on('click', '.like-btn', function(event) {
event.preventDefault();
alert('testlink');
});

Can't detect changed id

When I change the id of a button I cannot find the new id with on.("click"). The function console.log() does detect that it's changed but I cannot detect it with the on() function.
HTML:
<form id="formName" action="" method="post">
<input type="submit" id="submitBtn" value="Submit" />
</form>
<button id="change">Change</button>
JS:
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
});
$("#formName").submit(function(e){
e.preventDefault();
});
$("#NewBtn").on("click", function(){
alert("Hello");
});
So I need it to alert "Hello" after I have clicked on change. It does change the id I checked that with inspect element.
Fiddle: http://jsfiddle.net/WvbXX/
Change
$("#NewBtn").on("click", function(){
to
$(document).on("click", "#NewBtn", function(){
The reason for this is that you're wanting to use the delegate form of .on(). This call is a little different in that it takes a "string" as the second parameter. That string is the selector for your "dynamic" element while the main selector need either be a parent container (not created dynamically) or the document itself.
jsFiddle
you are setting onclick event for newBtn on load of page for the first time but unfortunately newBtn not available that time. hence after changing the id it will not trigger onclick function for newBtn.
you can do one thing to make it work, set onclick event for newBtn inside the same function where you are changing the id like below.
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
// set on click event for new button
$("#NewBtn").on("click", function(){
alert("Hello");
});
});
.attr() function does not have a callback and thus it cannot be checked unless you setup an interval using setInterval but the function itself executes pretty soon so you are not going to need it.
For solving the problem in hand event delegation proposed by tymeJV is the right way to do it.

Fancybox form ajax submit, only one ajax request

I've a question about ajax submitting.
I have a html form
<div style="display:none">
<form id="myform" method="post" action="">
<input type="text" id="name" />
<input type="submit" id="sbmt" />
</form>
</div>
And button to open the fancybox:
<a id="sbtfancybox" href="#myform">
<input type="button" value="Add new"
onClick="defineFancybox();" />
</a>
And i define a fancybox with jquery:
<script type="text/javascript">
function defineFancybox() {
$('#sbtfancybox').fancybox({
//...some json parameters
});
$('#myform').submit(function() {//the main problem is here
//....calling an ajax
return false;
});
}
</script>
My question is that how to do $('#myform').submit(..) that the submit always is called once, not that if i open fancybox the first time, the $('#myform').submit() is called once, if i open the fancybox the second time, the $('#myform').submit() is called twice, if i open the fancybox the third time then $('#myform').submit() is called tree times etc.
Thank you
jQuery event handlers don't override each other, even in the case where you're binding the same function again. Every time you call this code:
$('#myform').submit(function() {//the main problem is here
//....calling an ajax
return false;
});
another event handler gets added. Since that code is in the function that is called when you click on your button, the first click results in one event handler. The second click adds another one, so you now have two. The third click adds another, so you have three...
Since the form doesn't appear to be dynamically created you can just bind the single event handler when the page loads:
$(document).ready(function() {
$('#myform').submit(function() {
//....calling an ajax
return false;
});
});
Then move it out of the defineFancybox() function.
If you absolutely have to keep the event handler binding inside that function, then you can use the .off() (or .unbind() if you're using a version prior to 1.7) function to remove any existing event handlers before binding the new one:
$('#myform').off('submit').submit(function() {
//....calling an ajax
return false;
});
Have you tried with .one() handler:
$('#myform').one('submit', function() {//This will make it submitted once
//....calling an ajax
return false;
});
You can do something like
$('#myform').unbind('submit');
$('#myform').bind('submit',function() {//the main problem is here
//....calling an ajax
return false;
});
You may try the following
$("#myform").each(function(i) {
var handler = i.on("submit", function() {
handler.stop();
// do stuff
});
// other stuff
});

jQuery ajax defined actions

When I'm loading some content through ajax it returns an jQuery .click event and some elements. But when the ajax content is loaded a couple of times and I click the the button that is bound to the .click event, the action is executed a couple of times.
For example the ajax content is:
<script type="text/javascript">
$('#click').click(function() { alert('test') });
</script>
<input type="button" id="click" value="click here">
If this is refreshed 5 times and I click the button I will get 5 alert boxes.
Is there a workaround for this?
You can use the unbind function just before the click, something like this:
$('#click').unbind('click').click(function() { alert('test') });
That should let only one function associated with the click
The JQuery one method unbinds the handler after it is invoked:
$('#click').one("click",function() { alert('test') });
More info:
http://docs.jquery.com/Events/one

Categories

Resources