Single .on click for multiple elements - javascript

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

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

Jquery issue with variable

I have the following example: http://jsfiddle.net/gespinha/yTjUL/13/
The variable should be triggered on click, making the link change class from on to off and change colour from red to green. But instead it starts already green, thus making the function useless.
Why does it not work?
HTML
<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>
JQUERY
$(document).ready(function () {
var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});
});
You seem to be under the impression that the variable will store a chain of actions to perform later, when the variable is 'called,' but that's not (clearly) what happens: the first line, within the ready() handler, in the var assignment, finds the .on element and performs the actions you specify, storing the .on element(s) in the variable (as jQuery methods almost all return the this object).
Instead:
$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});
Or, more simply (if you want to toggle between 'states') use toggleClass() and $(this) (rather than selecting from the whole of the document each time the user clicks the given element):
$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});
Also, rather than using javascript:void(0) in the href, simply use jQuery to prevent the default action, with:
$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});
JS Fiddle demo.
References:
click().
event.preventDefault().
toggleClass().
It doesn't work that way, the variable will just contain the result of whatever methods you called, and for jQuery that means the element will be returned, so the variable $myVar only equals $(document) inside the event handler, it does not call the chained methods again.
You have to do:
$(document).ready(function () {
$('#link').on('click', function () {
$('.on').toggleClass('on off');
});
});
$(document).ready(function () {
$('#link').click(function () {
$(".on").addClass("off").removeClass("on");
});
});
As Guilherme Sehn noted, the $myVar variable is not needed. Just put your code in the click event. In addition, the link selector needs to be "#link", not "link".
By doing this, you'll be executing these actions and storing the return value (which will be the jQuery elements) inside $myVar. You can just put your code inside the click trigger function.
$('#link').click(function () {
$('.on').addClass('off').removeClass('on');
});
Also, you forgot the # before your ID. Without that your code will select link tags, not the element with the id link. And you do not need to explicity use $(document).find('.on') as all DOM elements are inside it.
I guess you meant $("#link")... and not $("link")
And if I understand right - the full script should be:
$(document).ready(function(){
$("#link").click(function(){
$(".on").addClass("off").removeClass("off");
});
});
You don't invoke the function and your selector is wrong.
$(document).ready(function () {
$('#link').click(function () {
$(document).find('.on').addClass('off').removeClass('on');
});
});

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

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...
}

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