Javascript Function being triggered by onClick check - javascript

I was wondering if there is a way for a function to check if it was triggered by the onClick method?
function check(id) {
if(onClick()) {
alert('thanks for clicking!');
}
}
I've tried to find this but I can't seem to come across anything.
Thanks!

Try this, this will give the type of event occured. Then you can match whether it was click or mousemove or mousedown or anything
<body onclick="eventType(event)">
function eventType(event)
{
alert(event.type); // if you want to check for click then use if(event.type=='click')
}

If your function is used a callback for an event somewhere, it will get the event object as an argument. So you simple check if event.type is "click".
function check(e) {
if (e.type == "click") {
alert("Thanks for clicking me!");
}
}
var button = document.getElementById("a_button");
button.onclick = check;

Related

Removing Event Listeners Inside of a Function

I've got two vote buttons (yes/no), each with an event listener. If they click no, I want to remove the yes. But that removeEventListener within the voteNo function appears to not be removing the voteYes listener.
Any idea what I'm doing wrong? Thanks in advance!
document.getElementById("voteButtonYesID").style.display = "inline";
document.getElementById("voteButtonNoID").style.display = "inline";
// listen for the no click
document.getElementById('voteButtonNoID').addEventListener('click', (e) => voteNo(e, direction),{once: true});
// listen for the yes click
document.getElementById('voteButtonYesID').addEventListener('click', (e) => voteYes(e, direction),{once: true});
function voteNo(e, direction) {
e.preventDefault();
// clear the voting buttons
document.getElementById("voteMessageID").style.display = "none";
document.getElementById("voteButtonYesID").style.display = "none";
document.getElementById("voteButtonNoID").style.display = "none";
document.getElementById('voteButtonNoID').removeEventListener('click', voteNo);
document.getElementById('voteButtonYesID').removeEventListener('click', voteYes);
EDIT: I feel like I am almost there. I'm able to pass the direction argument and use preventDefault(e) by using a named function. However...
Clicking the No button and the function executes, but it still does not remove the Yes button event listener. I have read that I can store the voteNo function in a variable so I can call it the same way for the add and remove event listeners, but I don't see how I could then pass my direction variable.
function voteNoClickCancel(direction) {
return function(e){
e.preventDefault()
document.getElementById('voteButtonYesID').removeEventListener('click', voteYesClickTrigger(direction));
voteResults('no',direction);
}
}
// listen for the no click
document.getElementById('voteButtonNoID').addEventListener('click', voteNoClickCancel(direction),{once: true});
// listen for the yes click
document.getElementById('voteButtonYesID').addEventListener('click', voteYesClickTrigger(direction),{once: true});
FINAL ANSWER:
I ultimately was not able to bring in the function argument direction, handle the preventDefault(e), and removeEventHandler. I'm sure there's a way to do it, but I took out the argument piece by making direction a global variable and not trying to pass it into the function.
const handleNoCancel = function voteNoClickCancel(e) {
e.preventDefault();
document.getElementById('voteButtonYesID').removeEventListener('click', handleYesTrigger,{once: true});
voteResults('no',hikeDirection); //hikeDirection is the new global variable
}
document.getElementById('voteButtonNoID').addEventListener('click', handleNoCancel,{once: true});
You never assigned voteNo as an event listener, you assigned anonymous function (e) => voteNo(e, direction)
You would have to declare this function before

preventDefault in function with more parameters?

I have a function that is run when clicking an input in the DOM. I want to stop the element from being checked until my function can approve it. I'm trying to do this using e.preventDefault(); or event.preventDefault(); (is there any difference?!) but I'm not succeeding, what am I doing wrong?
This is my code without the preventDefault-part.
$(document).on("click","[data-item]", function() {
cart.updateCart(this);
});
cart.updateCart = function(target) {
// do stuff and perhaps check the input element
}
I tried this, which is not working:
$(document).on("click","[data-item]", function() {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
event.preventDefault();
console.log(event); // returns MouseEvent -- is this even the correct "event" ?
// do stuff and perhaps check the input element
}
I think I'm not "getting" how this works. Perhaps someone can explain how this works and what I'm doing wrong?
event should be the first parameter passed into your click handler. So your code really should be like this.:
$(document).on("click","[data-item]", function(event) {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
event.preventDefault();
console.log(event); // returns MouseEvent -- is this even the correct "event" ?
// do stuff and perhaps check the input element
}
You can read more about preventing default actions here.

check multiple events - jQuery

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

jQuery unbind click event function and re-attach depending on situation

The code below I use to create a sliding menu. I need to know how to unbind the function attached to the click event and re-attach it some other time. (using jQuery 1.7.2)
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
});
});
The code below is what I have so far
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
//else re-attach functionality?
}
});
Thanks
Simply make a named function. You can go low tech here and back to basics to unbind and reattach specific events.
function doStuff()
{
if($(this).,next('.section').is(':visible'))
...
}
$('.header').on('click', doStuff);
$('.header').off('click', doStuff);
Instead of unbind and re-bind, I suggest you to add a simple class to .header and check for the class in the click handler. See below,
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('dontClick');
} else {
$('.header').removeClass('dontClick');
}
});
And in your .header click handler,
$('.header').click(function(){
if ($(this).hasClass('dontClick')) {
return false;
}
//rest of your code
If you insist on having a unbind and bind, then you can move the handler to a function and unbind/bind the function any number of time..
You can try something like this.
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('clickDisabled');
}
else
{
$('.header').removeClass('clickDisabled');
}
});
And then in the click handler check for this class.
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if(!$(this).hasClass('clickDisabled')){
...
...
}
});
});
Why not make that top section a function, and then call it in your else statement?
You could try setting a variable as a flag. var canClick = ($('#formVersion').val() != 'Print'); Then in the click handler for your .header elements check to see if canClick is true before executing your code.
If you still want to remove the handler you can assign the events object to a variable. var eventObj = #('.header').data('events'); That will give you an object with all the handlers assigned to that object. To reassign the click event it would be like $('.header').bind('click', eventObj.click[0]);
After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work.
So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.
Then in my Javascript i used the following to add an inline onclick handler:
$(element).attr('onclick','myFunction()');
To remove this at a later point from Javascript I used the following:
$(element).prop('onclick',null);
This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.
You could put all the code under the .click in a separated function
function headerClick(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
}
}
and then bind it like this:
$(document).ready(function(){
$('.section').hide();
$('.header').click(headerClick);
});
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
$('.header').click(headerClick);
}
});

jQuery event binding with accessibility in mind - click and keypress

Just a quick question, I seem to do this a lot:
$saveBtn.bind("click keypress", function(e)
{
if (e.type != "keypress" || e.keyCode == 13)
{
// Do something...
return false;
}
});
Is there a quicker way to bind an 'action' listener to a button? I want to always ensure my buttons with event listeners fire on both clicks and the enter key...this seems like it'd be a fairly common thing to want to do but found nothing on google. Any thoughts?
Thanks.
The click event doesn't actually handle the keypress in every case, it's the button that is making the click event work. When you use a div with a tabindex attribute to make it keyboard accessible, the click handler will not trigger when you press enter.
HTML
<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>​
jQuery
$("#click-only").click(function (e) {
addToBody(); // Only works on click
});
$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
addToBody(); // Works on click and keypress
}));
function addToBody() {
$("body").append($("<p/>").text("Submitted"));
}
function handleClickAndPress(myfunc) {
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
So to answer the question, I don't think there is a better way (that works in every case) other than yoda2k's solution.
By binding it with click will do the job, no need for keep press. Example
You could create a second function which handles the additional logic and pass your function as a parameter:
function handleClickAndPress(myfunc)
{
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
// do your stuff here
}));
If it's part of a form you could just listen for the "submit" event?

Categories

Resources