jQuery unbind after first click - javascript

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

Related

How to deactivate a nested anonymous function in Jquery

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

Single .on click for multiple elements

I have the following jquery...
$(".parentElem").on("click", "input[id*='myitem']", function() {
myfunction();
});
and
$(".parentElem").on("click", "input[id*='myotheritem']", function() {
myfunction();
});
These both work fine, but I don't want to have to list every clickable element separately... I'd much rather list them all at once - something like this...
$(".parentElem").on("click", "input[id*='myitem'], input[id*='myotheritem']", function() {
myfunction();
});
Is this possible? It doesn't seem to work for me.
The second argument in the .on() method is a CSS selector. So you don't have to pass in each individual element with their ID. You could just use a generic class or selector like this:
$('.parentElem').on('click', 'input', function(event) {
// Function body here
});
Simply don't use the delegation feature, instead do your own checking:
$(".parentElem").on("click", function() {
// check if event.target matches an element that you want to trigger on
});
This works for me:
$(".parentElem").find("input[id*='myitem'], input[id*='myotheritem']").each(function(){
$(this).click(function(){
myfunction();
});
});
DEMO

jQuery .on('change', function() {} not triggering for dynamically created inputs

The problem is that I have some dynamically created sets of input tags and I also have a function that is meant to trigger any time an input value is changed.
$('input').on('change', function() {
// Does some stuff and logs the event to the console
});
However the .on('change') is not triggering for any dynamically created inputs, only for items that were present when the page was loaded. Unfortunately this leaves me in a bit of a bind as .on is meant to be the replacement for .live() and .delegate() all of which are wrappers for .bind() :/
Has anyone else had this problem or know of a solution?
You should provide a selector to the on function:
$(document).on('change', 'input', function() {
// Does some stuff and logs the event to the console
});
In that case, it will work as you expected. Also, it is better to specify some element instead of document.
Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
You can use any one of several approaches:
$("#Input_Id").change(function(){ // 1st way
// do your code here
// Use this when your element is already rendered
});
$("#Input_Id").on('change', function(){ // 2nd way
// do your code here
// This will specifically call onChange of your element
});
$("body").on('change', '#Input_Id', function(){ // 3rd way
// do your code here
// It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});
Use this
$('body').on('change', '#id', function() {
// Action goes here.
});
Just to clarify some potential confusion.
This only works when an element is present on DOM load:
$("#target").change(function(){
//does some stuff;
});
When an element is dynamically loaded in later you can use:
$(".parent-element").on('change', '#target', function(){
//does some stuff;
});
$("#id").change(function(){
//does some stuff;
});
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
You can use 'input' event, that occurs when an element gets user input.
$(document).on('input', '#input_id', function() {
// this will fire all possible change actions
});
documentation from w3
$(document).on('change', '#id', aFunc);
function aFunc() {
// code here...
}

I'm having a jQuery onclick issue

So I'm going to explain this with an example.
I have a "like" button (class: .like) for my feed or stream. When the user clicks it ( using $(".like") ), it ajaxes it's way to refreshless insert the like into the database (using jQuery).
When it's inserted, I change the text to "Unlike" and the class to ".unlike".
However, when a user reclicks it, it just goes through the same function again, instead of going to the $(".unline").click function. Do I have to "update" the script or something?
For example:
$(".like").click(function(){
alert("Like!");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).attr("class", "like");
});
The problem is that it won't to the unlike function, it will just repeat the like function even though the attribute is changed.
That is because the "unlike" attr. hasn't been added to the dom when the script loaded. Try this:
<body>
<div class="like_it_or_not">
HELLO!
</div>
</body>
And the JS
$("body").on('click','.like_it_or_not', function(){
$(this).toggleClass('like', 'unlike');
if ($(this).hasClass('like')) {
alert('like');
} else if ($(this).hasClass('unlike')) {
alert('unlike');
}
});
If you don’t want to delegate your click event (which is over-engineering IMO), do a check in the handler:
$(".like").click(function(){
alert( $(this).hasClass('unlike') ? 'unlike' : 'like' );
$(this).toggleClass("unlike like");
});
http://jsfiddle.net/NScyM/
It should check for the 'unlike' class each time you click and toggle classes as expected.
The event binding occurs when you assign run the above code. You have to rebind the event every time, or, better yet, use event delegation:
$(document)on("click",".like",function(){
alert("Like!");
$(this).addClass("unlike");
$(this).removeClass("like");
});
$(document)on("click",".unlike",function(){
alert("Unike!");
$(this).addClass("like");
$(this).removeClass("unlike");
});
I think you will have to use live() or on() to make this work:
$(".like").live("click", function() {
$(this).removeClass("like").addClass("unlike");
});
$(".unlike").live("click", function() {
$(this).removeClass("unlike").addClass("like");
});
Try this one
$(".like").click(function(){
alert("Like!");
$(this).removeClass("like");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).removeClass("unlike");
$(this).attr("class", "like");
});
To keep my code clean on stuff like this, I assign a class that never changes and tie the click event to that. The styling classes simply act as CSS changes. For instance:
<button class="vote like">button text</button>
$('.vote').click(function () {
var alertText = ($(this).hasClass('like')) ? 'Like!' : 'Unlike!';
alert(alertText);
$(this).toggleClass('like').toggleClass('unlike');
});
Try this
$(document).on('click', '.like', function(){
alert("Like!");
$(this).html('Unlike').removeClass("like").addClass("unlike");
});
$(document).on('click', '.unlike', function(){
alert("Unlike!");
$(this).html('Like').removeClass("unlike").addClass("like");
});
DEMO.
The unlike click event handler has not been associated with the new item. If you're going to be changing the class dynamically like that you're going to want to look at the (jQuery on handler)[http://api.jquery.com/on/]
$(document).on('click',".like", function(){
alert("Like!");
$(this).addClass("unlike").removeClass('like');
});
$(document).on('click',".unlike",function(){
alert("Unlike!");
$(this).addClass("like").removeClass('unlike');
});

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