How to prevent jQuery duplicate function being called - javascript

I have a jQuery on('click') function like this:
function enabled_click() {
$('.btn_enabled').on('click', function() {
alert('CLICKED');
});
}
and then I have another post function like this
$(document).on('click', '.btn_add_link', function(e) {
var url = 'www.xxx.my-function';
post_data(url, function(data) {
if (data.status == 'success') {
$('#my_wrapper').append(data.response);
enabled_click();
} else {
alert('error');
}
});
return false;
});
The post function will append another .btn_enabled button. If i did not call the enabled_click() function on the success post, then the newly added .btn_enabled would not be able to trigger the onclick function.
But if I call the enabled_click() function like i did above, the already existing .btn_enable will then call the onclick function twice and alert CLICKED twice. Is there any way to make it so it only alerts once?

Event delegation by binding to a common parent, as answered by #qs1210, is a possible solution, and a very efficient one (because there's only one common handler instead of one per element). But depending on the code, it may require more changes.
As a compatible "drop-in replacment" just unbind the event handler before binding again. To achieve this in an easy and stable way, you can use jQuery's "namespace" feature for event names (see .on(), "Event names and namespaces"):
function enabled_click(){
$( '.btn_enabled' )
.off('click.some_namespace')
.on('click.some_namespace'), function() {
alert('CLICKED');
});
}
Note: if you extract the event handler into its own function and use that as second parameter to .off(), you could omit the namespace:
function click_handler(){
alert('CLICKED');
}
function enabled_click(){
$( '.btn_enabled' )
.off('click', click_handler)
.on('click', click_handler);
}
But this only works it the click_handler variable is "stable": depending where and when the click handler is defined, the variable (click_handler in this example) could be re-assigned and .off() couldn't detach the previous handler anymore.
Follow-up: in your example, you only apply the event handler to newly appended elements ($('#my_wrapper').append(data.response)). You could alter enabled_click to explicitly take the new element(s) as an argument:
function enabled_click($element){
$element.find('.btn_enabled' ).on('click', function() {
alert('CLICKED');
});
}
and call it like this:
var $newElement = $(data.response);
$('#my_wrapper').append($newElement);
enabled_click($newElement);
Now the event handler gets attached to new elements only, and not to already existing which have the event handler already attached.
(I'm using $ as prefix for all my variables holding jQuery collections, in order to distinguish them from pure DOM nodes)

Your can write like this
document.on('click', '.btn_enabled', function() {
alert('CLICKED');
})`
delegate event to dom, it makes everything harmony.

Related

Firing a function with a newly added class

I've tried to simplify it, simple enough to make my question clearer.
The alert 'I am a boy' didn't popup with even after the addClass has been executed.
Here is my code:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
$(".second").click(function () {
alert('I am a boy');
});
<button class="first">On</button>
This behavior is because you are apply a class to an element after the DOM has loaded, in other words dynamically. Because of this, your event listener attached to the control for '.second' isn't aware of the newly added class and doesn't fire when you click on that control.
To fix this, you simply need to apply your event listener to a parent DOM object, typically $(document) or $('body'), this will ensure it is aware of any children with dynamically added classes.
As George Bailey said, you can refer here for a in depth explanation.
In regards to your specific code, the fix is to simply adjust it as so:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
/* Changed this:
$(".second").click(function () {
alert('I am a boy');
});
*/
// To this:
$(document).on('click', '.second', function () {
console.log('I am a boy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">On</button>
The function you pass to $.post doesn’t run until later (a callback). So the class is added after you try to select it. Do it inside the callback, the same way you added the class (and you don’t need to select that class, just use $this)

jQuery override an on() event with another on() event

I have 2 files, file 1 (head.tpl) contains this default function operation
$(document).on("click", "#blackout", function(){
closeSkyBox();
});
That is the default operation I want to run, and it works.
On my second page, I would like to override the operation that is in head.tpl with this:
$(document).on("click", "#blackout", function(){
closeSkyBox(function(){
pev_for_country = '';
});
});
So, now when I test the code, each one runs, so If I were to place an alert (for testing reasons) I get two alert boxes. How can I make it so only the one in the second page runs, and the one in head.tpl is disabled. Then when I don't override it say on a third page, the one in head.tpl runs?
Looks like you're looking for jQuery's .off
$(document)
.off('click', '#blackout')
.on('click', '#blackout', function () {
// ...
});
You can use .off to remove all event handlers, but you should be cautious: what if other libraries add event handlers that you don't want to remove subscribe to this event? Also, if you add an additional event handler at a later date, this would obliterate it.
A better approach, I think, is to create a function that you can override:
function blackoutClick() {
closeSkyBox();
}
And set up your click handler:
$(document).on("click", "#blackout", function(){
blackoutClick();
});
Or, as Paul pointed out in the comments below, you don't even need to wrap that handler in an anonymous function, you can just use the cleaner:
$(document).on("click", "#blackout", blackoutClick );
Then, in your second page, you can just modify that function:
function blackoutClick() {
closeSkyBox(function(){
pev_for_country = '';
});
I believe another way to do it is also to set the event to null...
$(document).on('click', '#blackout', null);
before you re-set it on your second page.

Javascript, Jquery append functions to an event

I have a function that is associated with an event, say onfocus() and in some cases, I want to be able to execute the default function as well as one or more additional functions.
So I don't want to replace the original function, but I want to append another so that both functions will fire.
<div id="mydiv" onfocus="alert('hello');">
if(something == somethingelse) $('#mydiv').onFocus += "alert('world');"
So in this example, sometimes just Hello will Fire and sometimes Hello and then World will both fire.
I'm just using onfocus() and alert() as an example, these would actually be functions that I have defined.
How do I go about doing this ?
Use jQuery to add a focus event handler
<script>
$('#mydiv').on('focus', function(){
//do soemthing
})
</script>
If you work with jQuery don't use inline event bindings, use the following instead:
$("#mydiv").on("focus", function() {
alert("hello");
});
// add one more action for the same event
$("#mydiv").on("focus", function() {
alert("world");
});
You should do
$('#myDiv').on('focus', function(){alert('world')});
$('#mydiv').focus( function(){
})//This is for the elements which load while the page is loading
or
$('#mydiv').on('focus', function(){
}) //This is for the elements which will load dynamically after the page load completed.
If you don't want to use jQuery try this, its an pure javascript equivalent:
document.getElementById("mydiv").addEventListener("focus", function() { alert('world'); });
and if you want it to be compatible with IE8 and older you should try
var el = document.getElementById("mydiv");
if(el.addEventListener)
el.addEventListener("focus", function() { alert('world'); });
else
el.attachEvent("focus", function() { alert('world'); });
if you're using jQuery, you want to use on() to bind event handlers to elements as opposed to specifying them inline
$('#mydiv').on('focus', function () {
alert('hello');
});
$('#mydiv').on('focus', function () {
if (something === somethingelse) {
alert('world');
}
});
or combining into one handler function seems reasonable in this case
$('#mydiv').on('focus', function () {
alert('hello');
if (something === somethingelse) {
alert('world');
}
});
When specifying them inline as you have done, only one event handler can be bound to the event so if you want to bind multiple event handlers, you either need to bend the one event handler limitation to handle this or use another approach, such as DOM Level 2 events or an abstraction on top of it (such as jQuery's on() function).
Event handlers need to be bound when the element to which you are binding the handlers exists in the DOM. To do this, you can use jQuery's ready() function
// bind an event handler to the "ready" event on the document
$(document).ready(function () {
// ..... here
});
or shorthand
$(function () {
// ..... here
});

Prevent calling a function

I have two parts of scripts.
Part 1 :
$("mySelector").click(function() {
alert('you call me');
})
Part 2 :
$("mySelector").click(function() {
if(myCondition) {
//how can i prevent calling the first function from here ???
}
})
The whole problem, is that i have no access to part1. So i need to unbind the event allready specified in part 1, if myCondition is true, but otherwise i need to call the first function.
Thanks
UPDATE:
Thank you. I didn't know about stopImmediatePropagation(). But i feel, that there must be something like that :)
But actually in my case it doesn't work :(
Please have a look at my site
http://www.tours.am/en/outgoing/tours/%D5%80%D5%B6%D5%A4%D5%AF%D5%A1%D5%BD%D5%BF%D5%A1%D5%B6/Park-Hyatt-Goa/
Under the hotel description tab i have cloud carousel, when i click on not active image (not the front image), as you can see i'm consoling that i stopImmediatePropagation() there, but the event however calls :(
If your handler is registered first, then you can use event.stopImmediatePropagation like this:
$("mySelector").click(function(event) {
if(myCondition) {
event.stopImmediatePropagation();
}
})
Be aware that this will also stop event bubbling, so it will also prevent click handlers on parent elements from being invoked.
Update: If this does not work, then your handler is attached after the one you want to control. This is a problem that makes the solution much more difficult. I suggest seeing if you can bind "before the other guy", otherwise you will have to unbind the existing handler and then conditionally invoke it from within your own by retaining a reference to it. See jQuery find events handlers registered with an object.
No access:
$("#mySelector").click(function() {
alert('you call me');
})
Access:
var myCondition = true, //try false too
fFirstFunction = $("#mySelector").data("events").click[0].handler;
$("#mySelector").unbind("click");
$("#mySelector").click(function() {
if(myCondition) {
alert(myCondition);
} else {
$("#mySelector").click(fFirstFunction);
}
});
Look at this example
You can call
$('mySelector').unbind('click');
to get rid of all the click handlers. If your script is loaded after the other one (which appears to be the case), then that should do it. However note that it does unbind all "click" handlers, so make sure you call that before you add your own handler.
If you can't ensure your handler is attached first, try the following code:
var events = $('mySelector').data("events"); //all handlers bound to the element
var clickEvents = events ? events.click : null;//all click handlers bound to the element
$('mySelector').unbind('click'); //unbind all click handlers
//bind your handler
$("mySelector").click(function(e) {
if (myCondition) {
//do what you want
} else {
//call other handlers
if (clickEvents) {
for (var prop in clickEvents)
clickEvents[prop].call(this, e);
}
}
})
Update:
Above code is for jQuery 1.3.2
Above code is based on internal implementation of jQuery 1.3.2, so please check it carefully once you update jQuery.
return false;
-or-
event.preventDefault();

Adding a function to onclick event by Javascript!

Is it possible to add a onclick event to any button by jquery or something like we add class?
function onload()
{
//add a something() function to button by id
}
Calling your function something binding the click event on the element with a ID
$('#id').click(function(e) {
something();
});
$('#id').click(something);
$('#id').bind("click", function(e) { something(); });
Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).
$('#id').live("click", function(e) { something(); });
Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)
$('#id').attr("onclick", "something()");
Documentation
Click
Bind
Live
Attr
Yes. You could write it like this:
$(document).ready(function() {
$(".button").click(function(){
// do something when clicked
});
});
$('#id').click(function() {
// do stuff
});
Yes. Something like the following should work.
$('#button_id').click(function() {
// do stuff
});

Categories

Resources