How to pass preventDefault call to other event? - javascript

When the event occurs, some other event is triggered by its name. In some cases the second handler can call preventDefault. How to pass this call to original event?
https://jsfiddle.net/edgv8qur/1/
$("button").click(function (event) {
$("body").trigger("some-custom-event");
// If the custom event was prevented, prevent original one too
if (true) { // How to check?
event.preventDefault();
}
})
$("body").on("some-custom-event", function (event) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
} else {
console.log("allow");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Test</button>
PS: Same question in Russian.

You can pass an array of arguments to trigger() which will be passed to the event handler set in on(). Here is how you do it:
$("button").click(function (event) {
function cb(prevent) {
// If the custom event was prevented, prevent original one too
if (prevent) {
event.preventDefault();
}
}
$("body").trigger("some-custom-event", [cb]);
})
$("body").on("some-custom-event", function (event, cb) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
cb(true);
} else {
console.log("allow");
}
})
You can find out more about trigger() here.
UPDATE:
If you dont want to edit the handlers this is the way to go:
$("button").click(function (event) {
var event = jQuery.Event('some-custom-event');
$("body").trigger(event);
if (event.isDefaultPrevented()) {
event.preventDefault();
console.log("Prevented");
} else {
console.log("Allowed");
}
})
$("body").on("some-custom-event", function (event) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
} else {
console.log("allow");
}
})
event.isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.

Related

Trigger a keyup event function on meeting a certain condition in vanilla javascript

I have a piece of code where the user when he/she presses NumpadEnter key, a certain function triggers:
document.addEventListener("keyup", function(event) {
if (event.code === "NumpadEnter") {
//some logic here
}
}
Now I want to trigger this keyup function when a certain condition is met:
if(flag == true){
//trigger the keyup listener
}
How do I do that?
Don't trigger the event. Instead place the logic in a separate function that both the event handler and the other code will call:
function performAction() {
// logic here
}
document.addEventListener("keyup", function(event) {
if (event.code === "NumpadEnter") {
performAction();
}
}
// Now I want to trigger this keyup function when a certain condition is met:
if (flag == true){
performAction();
}
Put the keyup listener inside the flag checker. Then, pass a function to handle the event. Have that function as shown here:
function handleEvent(event) {
if (event.code === "NumpadEnter") {
//some logic here
}
}
if(flag == true){
//trigger the keyup listener
document.addEventListener("keyup", handleEvent)
}

Call a onkeyup function when click on other button jQuery

I have function which has keyup event on input field which is working fine.
I want to trigger this function also upon click on other button.
Here is my function
function validateChild(el) {
var validated = {};
console.log('Remove button clicked');
var dateOfBirthField = $(el).find('.date_of_birth');
$(dateOfBirthField).on("keyup", function () {
var dateOfBirthValue = $(el).find('.date_of_birth').val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
});
}
I'm calling this function on document load
function validateForms() {
$(document).find(".child-form").each(function () {
validateChild(this);
});
}
Here i have click event
.on('click', '.removeButton', function (event) {
validateForms();
});
When i click on this remove button it trigger but stop working after this
console.log('Remove button clicked');
How can i trigger keyup event also on this remove button, or there is better way to do this in javascript.
Can anyone help me with this?
Thanks
I have reviewed your three code blocks. Please try following three code blocks respectively.
Your function
function validateChild(dateOfBirthField) {
var validated = {};
var dateOfBirthValue = $(dateOfBirthField).val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
}
Call this function on document load
function validateForms() {
$('.child-form').on('keyup', '.date_of_birth', function() {
validateChild(this);
});
}
Click event
.on('click', '.removeButton', function() {
console.log('Remove button clicked');
$('.child-form .date_of_birth').each(function() {
validateChild(this);
});
});

Javascript .one event equivalent? Need to check when first transform transitionEnd fires

Was wondering if there's a javascript .one equivalent? Basically I need to detect when my transform fires but only once, at the moment the transitionend event fires twice which is messing up my transitions. I was hoping to use the event.propertyName but this just reads 'transform' which doesn't help. Example snippet here:
loader.addEventListener("transitionend", function(event) {
console.log(event); // fires twice
//if (event.propertyName === 'transform') {
togglePages(page);
//}
}, false);
You can create one:
function one(element, eventName, callback) {
element.addEventListener(eventName, function handler(event) {
element.removeEventListener(eventName, handler);
callback(event);
});
}
Now you can do:
one(loader, "transitionend", function(event) {
console.log(event);
togglePages(page);
});
You can use a simple control variable:
var didHappen = false;
loader.addEventListener("transitionend", function(event) {
if (!didHappen) {
togglePages(page);
didHappen = true;
}
});
Try removeEventListener.
Example:
loader.addEventListener("transitionend",function transition(event) {
loader.removeEventListener("transitionend", transition, false);
//if (event.propertyName === 'transform') {
togglePages(page);
//}
}, false);
Or
var transition = function (event) {
loader.removeEventListener("transitionend", transition, false);
//if (event.propertyName === 'transform') {
togglePages(page);
//}
};
loader.addEventListener("transitionend", , false);

Binding multiple events and run a function when all events are fired! JS, Jquery

I want to bind two mouse events to a function (mousedown and moucemove). But I want to run the function only if both events are fired.
This will bind each event to to the function: (It's not what i want)
$("#someid").bind("mousedown mousemove", function (event) { someFunction(); });
I can do this and it works:
$("#someid").bind("mousedown", function (event) {
someFunction();
$("#someid").bind("mousemove", function (event) {
someFunction();
});
});
$("#someid").bind("mouseup", function (event) {
$("#someid").unbind("mousemove");
});
Is there a better, quicker way to do this???
Bind only to the mousemove event. If the left mouse button is pressed while you move, event.which will be 1.
$(document).on('mousemove', function(e) {
if (e.which == 1) {
//do some stuff
}
});
I guess you want the mousemove handler work only when the mouse button is pressed down? If so, I'd suggest using some kind of boolean flag. You toggle its state on mousedown and mouseup events:
var flag = false;
$('#someid')
.on('mousedown', function(e) {
flag = true;
})
.on('mouseup', function(e) {
flag = false;
})
.on('mousemove', function(e) {
if (!flag) {
return false;
}
// else... do your stuff
});

jQuery wait for keyup after keydown

I'd like to trigger an event once after key down and a different event only after the down arrow key has been released, like so:
$('body').keydown(function (e)
{
if(e.keyCode==40)
{
//do something
}
$('body').keyup(function (d)
{
if(d.keyCode==40)
{
//do something else
}
}
}
This code only functions partially. The keydown is triggered continuously as the down arrow key is held.
I have a setInterval whose refresh rate I'm altering when I hold the arrow key. Unforunately setTimeOut isn't an option in this situation.
So my code looks something like this:
clearInterval(interval);
refresh = 100;
interval();
$('body').keydown(function (e) {
if(e.keyCode==40) {
//do something
}
return false;
})
.keyup(function(e) {
if(e.keyCode==40) {
//do something else
}
return false;
});
$('body').on('keyup', function (e) {
if(e.keyCode==40) {
//do something
}
// after first keyup set to handle next keydown only once:
$(this).one('keydown', function(e) {
if(e.keyCode==40) {
//do something else
}
});
});
If you need exactly trigger the event and not handle as it's in your example, then you need to use $.trigger() method.
If you want to do some action only once while the key remains pressed, simply keep track of that:
var arrowKeyDown = false;
$('body').keydown(function(e) {
if (e.which == 40 && !arrowKeyDown) {
arrowKeyDown = true;
// ...
}
});
$('body').keyup(function(e) {
if (e.which == 40) {
arrowKeyDown = false;
}
});
Demo: http://jsfiddle.net/utfwQ/
$('body').keydown(function (e)
{
console.log('down');
}​).keyup(function(e){console.log('up')});​​​​
If you really need to remove the keyup listener when you're done,
http://jsfiddle.net/CgmCT/
document.body.addEventListener('keydown', function (e) {
if(e.keyCode === 40){
console.log('key 40 down');
// key down code
document.body.addEventListener('keyup', function listener(d){
if(d.keyCode === 40){
document.body.removeEventListener('keyup', listener, true);
console.log('key 40 up');
// key up code
}
}, true);
}
}, true);​

Categories

Resources