How to combine different event triggers - javascript

I am new to jQuery and hope someone can help me with this.
I have a JS function that is triggered by various elements / classes with the difference that for some of them the event is triggered by a click and for others on keyup etc.
So far I have the following as an example which works as intended but I was wondering if there is a way to combine these as the only difference here is the trigger (click, keyup etc.) and to avoid duplicating code.
If there are any other suggestions to write this different please let me know as well.
My jQuery (example):
$(document).on('keyup', '.calcMinus, .calcPlus', function(e){
var row = $(e.target);
$(row).closest('table').find('td.calcSum').each(function(index){
calculateSums(row, index);
});
});
$(document).on('click', '.trAdd, .trDelete, .trDown, .trUp', function(e){
var row = $(e.target);
$(row).closest('table').find('td.calcSum').each(function(index){
calculateSums(row, index);
});
});
// ...
My JS function:
function calculateSums(row, index){
// do stuff
}
Many thanks in advance,
Mike

$(document).on('keyup', '.calcMinus, .calcPlus', combined);
$(document).on('click keyup', '.trAdd, .trDelete, .trDown, .trUp', combined);
function combined(e){
var row = $(e.target);
$(row).closest('table').find('td.calcSum').each(function(index){
calculateSums(row, index);
});
}

Extract the code from your event handler to a function, and call that from both of your existing handlers:
function handleEvent(row) {
$(row).closest('table').find('td.calcSum').each(function(index){
calculateSums(row, index);
})
}
$(document).on('keyup', '.calcMinus, .calcPlus', function(e){
handleEvent($(e.target));
});
$(document).on('click', '.trAdd, .trDelete, .trDown, .trUp', function(e){
handleEvent($(e.target));
});

Related

Call keypress event on button click?

I have below jquery code which is execute on keypress but I would like to execute same on button click. Please help me.
$('#itemselected').live('keypress', function() {
//some code which using $(this) also.
}
var myFunction = function(event){
console.debug(event);
//do your stuff here
};
$('#itemselected').on('keypress', function(event) {
myFunction(event);
}
$('#itemselected').on('click', function(event) {
myFunction(event);
}
Try to trigger the keypress on click
$('button').click(function() {
$('#itemselected').trigger('keypress');
});
I think you can just add 'click' to the list of event types like so:
$('#itemselected').on('keypress click', function() {
//some code which using $(this) also.
});

jQuery - Select All inputs and Bind Function

What's the most efficient way to select all input elements on a form and then attach a function to each which fires on focus out?
I am thinking along the lines of
var allInputs = $("form").each(function(){
$(this).find(':input').focusout(focusOutFunction);
});
var focusOutFunction = function() {
// do focus out things here
};
but not quite there yet.
Any advice would be much appreciated!
What about just:
$("form :input").blur(function() { });
Perhaps use event bubbling and delegation to catch the event on the inputs common container?
eg:
$('div.container').on('blur', function (e) {
console.log('I haz blurrd: ', e.target);
});

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

html + jquery ( Bind onclick event for execute action before onclick )

I have a question about "event click" and "order of execution".
I make a example here ( The HTML is generated by a external javascript ) :
HTML:
Comment​
JavaScript:
$(document).ready(function(){
$('#comments-replybutton').click(function(){
alert('2 attach event');
});
});​
I want that when do click in "Comment" first execute the action of jquery (bind event).
Is this possible?
I believe you're looking for preventDefault().
More here.
$(document).ready(function(){
$('#comments-replybutton').click(function(e){
e.preventDefault();
alert('2 attach event');
});
});​
$(document).ready(function(ev){
$('#comments-replybutton').click(function(ev){
alert('2 attach event');
ev.stopPropagation();
});
});​
You mean, like this?
Edit after comment
You can also name your function to unbind:
var myEventHandler = function myFunction(ev){
$(this).unbind(myFunction);
alert('attach event 2');
ev.stopPropagation();
}
$('#comments-replybutton').bind('click', myEventHandler);
// $(something).click(fn) is just a shorthand to $(something).bind('click', fn);
Edit 2
I guess you can kill off the original event easily, just by saying document.getElementById('comments-replybutton').onclick = "" or something similar. You can re-attach it by copying before:
var original_event_handler = $('#comments-replybutton')[0].onclick;
$('#comments-replybutton')[0].onclick = "";
$('#comments-replybutton').click(original_event_handler);
A bit dirty, but I'm too lazy to look it up :S preventDefault won't help you here, though.
http://jsfiddle.net/C37ka/
try this:
$(document).ready(function(){
$('#comments-replybutton').unbind('click').click(function(){
alert('2 attach event');
});
});​
and if you need also to execute the inline statement at the end, you will need something like this:
$(document).ready(function(){
var initialEvent = $('#comments-replybutton')[0].onclick;
$('#comments-replybutton').click(function(){
alert('2 attach event');
}).click(initialEvent);
});​

How to apply multiple events to the same function

I'm not the best at this jquery stuff. But I'm trying to seperate the action from the function so I can apply multiple events that cause the same function. Unfortunately this isn't working. Anyone know why?
Updated Function, but still errors
$(document).ready(function() {
var $info_items = jQuery('.checkbox.has_info, .has_info');
$info_items.click(function(event) {
$(this).show_text(event);
});
// I suspect it has something to do with this initalizer of the function here
jQuery.fn.show_text = function(event){
var $info_item = jQuery(this);
$info_items.filter(function(index){
return $(".hidden_text").css("display","block");
}).not($info_item).parent().next().next().hide("slow");
$info_item.parent().next().next().show("fast");
});
});
What is e, the event? You need to name the event argument to the click() function to use it. Also, to invoke show_text such that it has a this, you need to invoke it on an element:
$info_items.click(function (event) {
// 'this' is the element in $info_items which was clicked
// invoke show_text on the element in question
$(this).show_text(event);
});
You also have an extra ) on your final }); line.
You can use jQuery bind to attach several events to a single function.
$('#whatever').bind('mouseover focus click', function() {
your_custom_function();
});
Are you looking for something like this?
var handle = function(event) {
$(event.currentTarget).show_text(event);
};
$info_items.bind('click blur', handle);

Categories

Resources