How to pass event from one function to another in jQuery - javascript

I need to pass somehow the information about pressed Ctrl key on invoking the event by jQuery click function. I want invoke this with Ctrl key pressed.
$(selector).click();
This is simplified example:
https://jsfiddle.net/62mdur6o/
When you click on the first cell of table ("One") you do not get information about present Ctrl key in the event.
Is it possible to invoke click listener differently or to attach somehow this information to the event which will be passed to other listeners?

You can trigger event using:
$('#cell').click(function (event) {
event.stopPropagation();
var e = jQuery.Event( event, {ctrlKey: event.ctrlKey} );
$(this).next().trigger(e);
});
-demo-

Target each cells
$('.cells').click(function (event) {
if (event.ctrlKey) {
alert('ctrl pressed');
} else {
alert('just clicked');
}
});
updated fiddle

Related

eventListener firing multiple times and increasing

On a click function I have the option of playing audio.
The click is only fired once (after I added .off(), which I seem to have to do for every click event because I think there's something I fundamentally don't get about how javascript works) but the function added to the "ended" listener shows it is firing the number of times the button has been clicked. I presume .play() is also being fired multiple times.
These need to be inside the click event to get the id so how do I stop these kinds of things from happening, here and elsewhere when using js? Adding event.stopPropagation(), event.bubbles = false and .off() everywhere seems unnecessary (and in this case doesn't make a difference anyway).
$('.button').off().on('click', function(event){
event.stopPropagation();
event.bubbles = false;
var id = $(this).attr('id')
if ($(this).hasClass('hasAudio')) {
document.getElementById('audio_'+id).play();
document.getElementById('audio_'+id).addEventListener("ended", function(){
console.log("ended");
});
}
});
Move the ended event outside the click event,you are registering the event each time you click on the button
$('.button').on('click', function(event){
var id = $(this).attr('id')
if ($(this).hasClass('hasAudio')) {
document.getElementById('audio_'+id).play();
}
});
$('[id^="audio_"]').on("ended", function(){
console.log("ended");
});
Each time you click on the button a new event listener will be added to the ended event. To prevent that you can try defining the callback function before hand. That will prevent your event listener to be added in the event loop over and over.
An anonymous function has no signature, hence when you define the event with it, it will think that this is supposed to be a new event listener and invokes it multiple times. Check the working snippets to see the difference. Type something in the input box to see what is happening.
If this is confusing then removeEventListener can be the next option.
function ended(event){
console.log("ended");
}
$('.button').off().on('click', function(event){
event.stopPropagation();
event.bubbles = false;
var id = $(this).attr('id')
if ($(this).hasClass('hasAudio')) {
document.getElementById('audio_'+id).play();
document.getElementById('audio_'+id).addEventListener("ended", ended);
}
});
var input = document.getElementById('some');
function callback(event) {
console.log("PRINT");
}
input.addEventListener("keyup", callback)
// input.removeEventListener("keyup", callback)
input.addEventListener("keyup", callback)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="some" value="" >
Anonymous function as callback
var input = document.getElementById('some');
input.addEventListener("keyup", function(event) {
console.log("PRINT");
})
// input.removeEventListener("keyup", callback)
input.addEventListener("keyup", function(event) {
console.log("PRINT");
})
<input id="some" value="">
This fails because, every time you click the function, you add a new event listener to the button.
document.getElementById('audio_'+id).addEventListener("ended", function(){
console.log("ended");
This is repeatedly adding the event listener to the button.If you need this inside the click event, check to see whether it exists already. If it does, don't add it again.
Use global flag which defines if you want to pause or play. and also use preventDefault (in case of any inline click event used).
You have to remove the registered event listener after your task is completed.
document.getElementById('audio_'+id).removeEventListener("ended", function(){
console.log("ended");
});
Or what you can do is that move the logic for registering event listener outside the click event listener. Like this the event will be registered only once.
document.getElementById('audio_'+id).addEventListener("ended", function(){
console.log("ended");
});
}
$('.button').off().on('click', function(event){
event.stopPropagation();
event.bubbles = false;
var id = $(this).attr('id')
if ($(this).hasClass('hasAudio')) {
document.getElementById('audio_'+id).play();
});

How do you "bypass" mouse up?

I am trying to make it so that when a user clicks down, this happens.
In order,
Does something. (Not being specific, this isn't the important part.)
Mouse up is triggered.
Using: angular, html, css.
Not using: jQuery
Any suggestions?
Thanks!
You attach two event listeners, one while the user has the mouse pressed down mousedown. Once the user lets go the mouseup event is triggered. All mouse event listeners are passed an event object you can use to get information about the event ie: mouse x, and y positions.one of the methods available is event.preventDefault() this will stop the browser doing what it usually wants to do. Example: cmd/ctrl + s will cause the browser to save the html page. preventDefault will stop this.
document.addEventListener('mousedown' function (event) {
// Do something
})
document.addEventListener('mouseup', function (event) {
event.preventDefault()
})
To address OP comment:
var noMouseUp = true
document.addEventListener('mousedown', function () {
if (noMouseUp) {
// do something
noMouseUp = false
}
})
document.addEventListener('mouseup', function (event) {
if (!noMouseUp) {
noMouseUp = true
}
})
Use events.preventDefault(); in the mouseup callback.
Use, right after, event.stopPropagation(); to avoid the event passing to other layered elements.
bypassed_element.onclick = function(event){
event.preventDefault();
event.stopPropagation();
};

jQuery .on() running before value given

Why does .on() not get the value of the form input field (#forgot) before the keypress has happened.
$(document).ready(function() {
$(document).on('keypress', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});
When I type in the first character the alert shows no input. The second character leads to the value being only the first character. The .on() function seems to run before the key press is registered? How can I fix this or is there an alternative function?
keypress event triggered when you press a key. It will not wait for the value to come. Try with keyup. keyup gets triggered when you a key is released after pressing, till that time the value is proccessed. -
$(document).on('keyup', '#pass', function() {
keypress
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.
keyup
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
Simply change keypress to keyup:
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
console.log(value);
if (!value.length) {
console.log("Show");
$('#forgot').show();
} else {
console.log("Hide");
$('#forgot').hide();
}
});
});
You need the keyup event instead of the keypress.
So replace:
$(document).on('keypress', '#pass', function() {
With
$(document).on('keyup', '#pass', function() {
keypress event is triggered when the key is pressed before the key is up). So it won't get the complete value.
Use keyup
JSFIDDLE DEMO
HTML
<input id="pass">
JQUERY
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});

How to stop an event if not triggered directly?

Lets say there is a textbox and a button. On the click of button a function is executed, and on the focusout of textbox, the button is clicked. What I wanna know is, is there a way, I can determine that weather the user clicked the button, or it was triggered by focusout event of textbox, so that I may do some custom work in the click event, if it was triggered by focusout of textbox?
I could write some code, but I don't even have any idea where to begin with, I know the jQuery event and event.which property, but I wonder if it/they could be useful in this situation?
you can use event.target to determine which DOM element has initiated the event, then you can check if this is the button or the textbox.
check this out for more information: http://api.jquery.com/event.target/
from the documetation:
event.target
The target property can be the element that registered for the event
or a descendant of it. It is often useful to compare event.target to
this in order to determine if the event is being handled due to event
bubbling. This property is very useful in event delegation, when
events bubble.
This depends on how you're triggering the function from the textarea blur event, if you're simply triggering the click event using the following approach:
$('#btn').click(
function(e){
buttonActivation(e);
});
$('#txt').blur(
function(e){
$('#btn').click();
});
Then I'd suggest evaluating the originalEvent object to see what the original event was (if there was no originalEvent then the function was called by a programmatic click event, with jQuery; whereas if the originalEvent.type evaluates to click then the button must have been clicked.
function buttonActivation(e) {
if (!e) {
return false;
}
else {
var oEvent = e.originalEvent;
if (oEvent === undefined) {
console.log('Programmatic event');
}
else if (oEvent.type == 'click') {
console.log('User-initiated event');
}
}
}
JS Fiddle demo.
If, however, you're using something like the following (simply calling the same function from a different place):
$('#btn').click(
function(e){
buttonActivation(e);
});
$('#txt').blur(
function(e){
buttonActivation(e);
});
Then I'd recommend either directly assessing e.target or e.type:
function buttonActivation(e) {
if (!e) {
return false;
}
else {
var oEvent = e.type;
if (oEvent === 'blur') {
console.log('Programmatically-triggered event, on ' + oEvent);
}
else if (oEvent == 'click') {
console.log('User-initiated ' + oEvent + ' event');
}
}
}
JS Fiddle demo.
You can use the event.target. By default, jquery provides the event to the handler function.
Here's an example : jsfiddle
You can pass an additional parameters when triggering the event and check them in event handler.
So if you wrote
button$.trigger('click', 'hello');
then you can write the handler like
button$.on('click', function(e, someStr) {
console.log(someStr || 'Nothing passed');
// Obviously if someStr is undefined, the user clicked the button,
// otherwise the $.trigger() method has been called.
});

How to bind the enter/return key to user-defined function

I'm developing an application that runs on one page, and does not reload. I have a form with only an input type text, no submit button. I included the onchange event, after filling the textbox with data, I want to execute the function bound to the onchange event when I press enter, but the form is rather submitted and [it attempts to load a new page]. Please what do I do? Thanks
You can hook the keypress event on the text box and call your handler, and cancel the event to prevent the form submission:
$("selector_for_your_text_box").keypress(function(event) {
if (event.which === 13) {
// call your `change` logic here
// Cancel the event
return false;
}
});
Live example
This should work:
$(function() {
$('#yourInput').keypress(function(event) {
var key = event.keyCode || event.which;
if (key == 13) {
event.preventDefault();
// call your function here
});
});
Yuo can bind to the keypress event on the input:
$('#inputfieldid').keypress(function() {
alert('Handler for .keypress() called.');
});
Try the demo link http://jsfiddle.net/HDkJW/

Categories