check multiple events - jQuery - javascript

Suppose I want to run a function myFunction at each of the events $(document).ready, $(sometag).on('click',....). How can I construct a function that checks if any of those two events are triggered, and then run the method. Can I pass $(document) as an argument and then check $(document).isReady or check $(document).click(function(e){if (e.target.is($(some tag))) ...}). Is this correct ?

It's not easy to understand what the heck you are talking about, but it sounds like you're trying to attach an event handler and trigger it on document ready, and if so you'd do that like this :
$(document).ready(function() {
$(sometag).on('click', function() {
// do stuff
}).trigger('click');
});

If I understand you correctly:
function myFunc(event) {
if (event.type == 'ready')
console.log('It is a document.ready');
else if (event.type == 'click')
console.log('It is a click');
}
$(document).on('ready', myFunc).on('click', 'a', myFunc);
jsfiddle

from what i could understand from your question...
Jsfiddle: http://jsfiddle.net/patelmilanb1/eR4wG/1/
$('.checkbox').change(function (e) {
if (e.isTrigger) {
alert('not a human');
} else {
alert("manual check by human");
}
});
$('.checkbox').trigger('change'); //alert not a human because it is automatically triggered.

I may not understand your question very much, but try this:
$(function(){
$('div1,div2,#id1,#id2,.class1,.class2').click(function(){
// do something
yourFunction();
});
});

triggering function on multiple events of an element, you may try:
$('#element').on('keyup keypress blur change', function() {
...
});
and multiple function on multiple elements, try:
$('#element #element1 #element2').on('keyup keypress blur change', function() {
...
});

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

How to better handle events

If I have multiple events on an element I am currently handling those events as written here:
$("body").on("click", ".element", function(e) {
// Do something on click
});
$("body").on("change", ".element", function(e) {
// Do something on change
});
Is there a way to combine all the events on an element in one on() call? What is the best practice if there are multiple events associated with one element?
$("body").on("change click", ".element", function(e) {
// Can I detect here if it was change or click event and perform an action accordingly?
});
You can use the type property of the event to determine which logic to execute:
$('body').on('change click', '.element', function(e) {
if (e.type == 'click') {
// do something...
}
else if (e.type == 'change') {
// do something else...
}
});
Alternatively you can provide an object to on which contains the functions to bind with the event type names as the keys:
$('body').on({
click: function() {
// do something on click...
},
change: function() {
// do something on change...
}
}, '.element');
Personally I would use the latter method. The whole point of having a unified on() handler is negated when using a rather ugly if statement to split the event types.
Yes! jQuery passes the event object which contain the event information:
$("body").on("change click", ".element", function(e) {
console.log(e.type);
});
You can use the event.type. Some will say it's bad practice and others may find it useful.
$("body").on("change click", ".element", function(event) {
switch (event.type) {
case 'click':
break;
case 'change':
break;
default:
}
});
jQuery event.type
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="element" />

Don't work my jQuery code after append

Don't work my jQuery code after append. how can just change js code and worked it?
I don't use from ides "#aaa or #sss", How do without use them?
DEMO: http://jsfiddle.net/sq4kx/
html:
Click Me
<div id="aaa">
<div id="sss">
</div>
</div>
jQuery:
$('.qqq').on('click', function (e) {
e.preventDefault();
$('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
})
$('.auto_box').on('keyup change', '.de1', function () {
alert('This is ok');
})
Try this like,
$('#sss').on('keyup change', '.auto_box .de1', function () {
alert('This is ok');
});
Demo 1
Or
$('.qqq').on('click', function (e) {
e.preventDefault();
$('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
// bind event here
$('.auto_box').on('keyup change', '.de1', function () {
alert('This is ok');
});
});
Demo 2
Try:
$(document).on('keyup change', '.de1', function () {
alert('This is ok');
});
Updated fiddle here.
replace '.auto_box' with document.
$(document).on('keyup change', '.de1', function () {
alert('This is ok');
});
Reason:Why the above code works and yours does not?
1.You are dynamically adding elements.In simpler words,the element you appended did not exist when DOM was loaded.
2.You need to assign Event Delegation for any future addition of elements.The method that we usually use like .click(...) , .on(..) etc only applies to the elements that are currently in the DOM.
3.This is how you provide Event Delegation.
$(document).on('keyup change', '.de1', function(){.........})

How to combine keypress & on click function in JavaScript?

I have the following two functions:
$("input").keypress(function(event) {
if (event.which == 13) {
//code
}
});
$('#login_submit').click(function () {
//code
});
The code which is being used in the functions are EXACTLY the same code, basically code dublication. So i was wondering if there is a way to combine these functions with an OR statement??
Create your own callback and pass that to the event handlers.
var callback = function() {...};
$("input").keypress(function() {
if (event.which == 13) callback();
});
$('#login_submit').click(callback);
Add a class to your HTML
<input class="myClass">
<div id="login_submit" class="myClass" ></div>
Now you can write:
$(".myClass").bind("keypress click", function(){});
Or do this:
$("input").add("#login_submit").bind("keypress click", function(){});
Be aware that clicking on the input will also trigger this.
Why don't you do it like this?
$("input").keypress(function(event) {
if (event.which == 13) {
foospace.yourfunction();
}
});
$('#login_submit').click(function () {
foospace.yourfunction();
});
var foospace={};
foospace.yourfunction=function() {
alert("your code goes here!");
}
Edit:
The callback solution by #David is slightly more elegant.
I would chain the events like:
var watchCurrentCursorPosition = function (){
console.log("foo");
}
$("input").keypress(
watchCurrentCursorPosition
).click(
watchCurrentCursorPosition
);
For those who still are looking for an answer to the #Sino's question.
The code which is being used in the functions are EXACTLY the same code, basically code dublication. So i was wondering if there is a way to combine these functions with an OR statement??
JQuery .on() method is the way to go.
Description: Attach an event handler function for one or more events to the selected elements.
So your code could go like this:
$("input").on("click keypress", function(event) {
if (event.which === 13) {
event.preventDefault();
//code
}
});

What is the opposite of evt.preventDefault();

Once I've fired an evt.preventDefault(), how can I resume default actions again?
As per commented by #Prescott, the opposite of:
evt.preventDefault();
Could be:
Essentially equating to 'do default', since we're no longer preventing it.
Otherwise I'm inclined to point you to the answers provided by another comments and answers:
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
How to reenable event.preventDefault?
Note that the second one has been accepted with an example solution, given by redsquare (posted here for a direct solution in case this isn't closed as duplicate):
$('form').submit( function(ev) {
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
function(evt) {evt.preventDefault();}
and its opposite
function(evt) {return true;}
cheers!
To process a command before continue a link from a click event in jQuery:
Eg: Click me
Prevent and follow through with jQuery:
$('a.myevent').click(function(event) {
event.preventDefault();
// Do my commands
if( myEventThingFirst() )
{
// then redirect to original location
window.location = this.href;
}
else
{
alert("Couldn't do my thing first");
}
});
Or simply run window.location = this.href; after the preventDefault();
OK ! it works for the click event :
$("#submit").click(function(event){
event.preventDefault();
// -> block the click of the sumbit ... do what you want
// the html click submit work now !
$("#submit").unbind('click').click();
});
event.preventDefault(); //or event.returnValue = false;
and its opposite(standard) :
event.returnValue = true;
source:
https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue
I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
I would suggest the following pattern:
document.getElementById("foo").onsubmit = function(e) {
if (document.getElementById("test").value == "test") {
return true;
} else {
e.preventDefault();
}
}
<form id="foo">
<input id="test"/>
<input type="submit"/>
</form>
...unless I'm missing something.
http://jsfiddle.net/DdvcX/
This is what I used to set it:
$("body").on('touchmove', function(e){
e.preventDefault();
});
And to undo it:
$("body").unbind("touchmove");
There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.
Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).
As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.
See below for an explanation:
;(function($, window, document, undefined)) {
$(function() {
// By default deny the submit
var allowSubmit = false;
$("#someform").on("submit", function(event) {
if (!allowSubmit) {
event.preventDefault();
// Your code logic in here (maybe form validation or something)
// Then you set allowSubmit to true so this code is bypassed
allowSubmit = true;
}
});
});
})(jQuery, window, document);
In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.
This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.
Here's something useful...
First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.
Google
<script type="text/javascript">
$(document).ready(function() {
$("#link").click(function(e) {
// Prevent default action
e.preventDefault();
// Here you'll put your code, what you want to execute before default action
alert(123);
// Prevent infinite loop
$(this).unbind('click');
// Execute default action
e.currentTarget.click();
});
});
</script>
None of the solutions helped me here and I did this to solve my situation.
<a onclick="return clickEvent(event);" href="/contact-us">
And the function clickEvent(),
function clickEvent(event) {
event.preventDefault();
// do your thing here
// remove the onclick event trigger and continue with the event
event.target.parentElement.onclick = null;
event.target.parentElement.click();
}
I supose the "opposite" would be to simulate an event. You could use .createEvent()
Following Mozilla's example:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var cancelled = !cb.dispatchEvent(evt);
if(cancelled) {
// A handler called preventDefault
alert("cancelled");
} else {
// None of the handlers called preventDefault
alert("not cancelled");
}
}
Ref: document.createEvent
jQuery has .trigger() so you can trigger events on elements -- sometimes useful.
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.
$('.btnEdit').click(function(e) {
var status = $(this).closest('tr').find('td').eq(3).html().trim();
var tripId = $(this).attr('tripId');
if (status == 'Completed') {
e.preventDefault();
alert("You can't edit completed reservations");
} else if (tripId != '') {
e.preventDefault();
alert("You can't edit a reservation which is already attached to a trip");
}
//else it will continue as usual
});
jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.
jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.
$( selector ).on("submit.my-namespace", function( event ) {
//prevent the event
event.preventDefault();
//cache the selector
var $this = $(this);
if ( my_condition_is_true ) {
//when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
$this.off("submit.my-namespace").trigger("submit");
}
});
now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..
you can use this after "preventDefault" method
//Here evt.target return default event (eg : defult url etc)
var defaultEvent=evt.target;
//Here we save default event ..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
You can always use this attached to some click event in your script:
location.href = this.href;
example of usage is:
jQuery('a').click(function(e) {
location.href = this.href;
});
In a Synchronous flow, you call e.preventDefault() only when you need to:
a_link.addEventListener('click', (e) => {
if( conditionFailed ) {
e.preventDefault();
// return;
}
// continue with default behaviour i.e redirect to href
});
In an Asynchronous flow, you have many ways but one that is quite common is using window.location:
a_link.addEventListener('click', (e) => {
e.preventDefault(); // prevent default any way
const self = this;
call_returning_promise()
.then(res => {
if(res) {
window.location.replace( self.href );
}
});
});
You can for sure make the above flow synchronous by using async-await
this code worked for me to re-instantiate the event after i had used :
event.preventDefault(); to disable the event.
event.preventDefault = false;
I have used the following code. It works fine for me.
$('a').bind('click', function(e) {
e.stopPropagation();
});

Categories

Resources