How to deactivate a nested anonymous function in Jquery - javascript

I have the following code:
$('#button-a').click(function(){
$('#button-b').click(function(){
alert('something');
});
});
$('#button-b').click(function(){
// do something
});
How can I deactivate the nested #button-b function after I have clicked #button-a, so only the last #button-b function (not nested) activates when i click #button-b and not them both?

Try this using .on() and .off() event handlers.
$('#button-a').click(function(){
$('#button-b').off('click'); //unbind the click event of the #button-b
$('#button-b').click(function(){
alert('something');
});
});
$('#button-b').on('click',function(){
// do something
});

In order to accomplish this, your function cannot be anonymous. You need to use the form of off which specifies the handler to remove. Rewriting your code a bit, it'd look something like this:
function myFunc() {
alert('something');
}
$("#button-a").click(function() {
$("#button-b").click(myFunc);
});
$("#button-b").click(function() {
// do something
});
To remove the handler, you'd use:
$("#button-b").off('click', myFunc);
I'm not quite sure where you want this to occur, but the above line of code will work anywhere that the DOM has been loaded and myFunc is in scope.

If you feel you definitely need an anonymous handler here, you can use event namespace for your task - http://api.jquery.com/on/
$('#button-b').on('click.nestedClick', function(){
alert('something');
});
// and unbind it at some point:
$('#button-b').off('click.nestedClick');

$('#button-a').click(function(){
$('#button-b').trigger('click');
});
$('#button-b').click(function(){
// do something
});
Change your code like this so it call your last function for button-b when you click on button-a

Related

jQuery unbind after first click

This causes multiple buttons to take action:
$(document).on("click", ".file-this-email", fileThisEmail);
When fileThisEmail runs, I'd like to remove it from ONLY the current one (there are others on the page that still need it):
window.fileThisEmail = function(e) {
console.log('this was clicked');
}
I tried off, but couldn't seem to get it right. Any ideas?
In this case, you have to make the current element no longer match the ".file-this-email" selector.
$(document).on("click", ".file-this-email", function() {
console.log('this was clicked');
$(this).removeClass("file-this-email");
});
An alternative would be to add a filter to the selector, with the same concept.
$(document).on("click", ".file-this-email:not(.clicked)", function() {
console.log('this was clicked');
$(this).addClass("clicked");
});
Or, don't use delegation for this particular case. Delegation isn't some new technology that replaces direct binding, it's just another way of binding events. If used correctly, it can make code more efficient. The opposite is true too; if used incorrectly, it can make the code very bloated.
$(".file-this-email").on("click", function () {
console.log("this was clicked");
$(this).off("click");
});
// or even better (thanks #overachiever):
$(".file-this-email").one("click", function () {
console.log("this was clicked");
});
Bind individual handlers to each element like this:
$(".file-this-email").one("click",fileThisEmail);
What you should do is
$(document).on("click", ".file-this-email", fileThisEmail);
change this to
$(document).ready(function(){
$(".file-this-email").on("click",fileThisEmail);
$(".file-this-email").click(function(){
$(this).off("click",fileThisEmail);
});
});
The .one() method is good for this. http://api.jquery.com/one/
$(document).ready(function(){
$('.file-this-email').one('click', fileThisEmail);
});

Is it possible to change a .click() function in JQuery?

If I have a .click() function in the header of my page, is it possible to overwrite it later in the page?
For example if I have this in the header:
<script>
$("document").ready(function() {
$("a.lol").click(function () {
alert("aaa");
});
});
</script>
Would it be possible to change $("a.lol") to alert something else, and not alert "aaa"?
Try this,
$("document").ready(function() {
$("a.lol").click(function () { // initially the click event
alert("aaa");
});
$("a.lol").off('click');// off the click event
$("a.lol").on('click',function () { // again bind new click event with on()
alert("new click");
});
});
Read on() and off()
You can use .unbind() and then "put it back" adding a new handler.
$("a.lol").unbind('click');
Use .off()
$("a.lol").off('click');
and to add back use .on()
$("a.lol").on('click',functionName);
or
$("a.lol").on('click',function () {
//code here
});
Use $("a.lol").off('click') to remove all click handlers. Afterwards, you can install new ones.
For older versions of jQuery, use unbind()
Yes, you will have to remove the current handler with off() and then call click() again with the new handler.
// Some code
$("a.lol").off("click")
$("a.lol").click(function () {
alert("ooo");
});
PS: Depending on your use case you could maybe use one() which would trigger the handler only once and then remove itself

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
});

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