Invoke the click handler of a button - javascript

I'm trying to invoke the click of a button programatically using JavaScript. My code is:
$(document).ready(function() { autoload(); });
function autoload() {
var button = $("#button");
var video = $("#video");
var evnt = button["onclick"];
// Set the click handler of the button
button.click(function () {
video.get(0).play();
});
// Call the button's click handler
if (typeof button.onclick == "function") {
button.onclick.apply(button);
}
}
But for some reason this is not working, the click handler is not called.

Events in jQuery are different than native DOM events.
You should use button.click() or button.trigger("click").

Related

JavaScript: How prevent dblclick (Double Click) to also fire a single click event

I want avoid that double click also fire a single click event.
A simple solution i found is to delay the click with a timer and destroy the timer if a double click is fired.
var pendingClick;
function myclick(){
clearTimeout(pendingClick);
pendingClick = setTimeout(function(){
console.log('click');
}, 500);
}
function mydblclick(){
clearTimeout(pendingClick);
console.log('double click');
}
<div onclick="myclick()" ondblclick="mydblclick()">Double Click Me!</div>
But this solution is based on timing, if the double click is too slow (>500ms) it also fire a single click.
There is a stable solution for handle both click and double click?
Double-clicking in itself is "based on timing", even in the standard implementation of dblclick / ondblclick. There will always be the issue of a single-click being fired if the double-click is "too slow". What is "too slow"? 300ms? 500ms? 1000ms? Your double-clicks may be only 50ms apart, while my mom's double-clicks are 1-2 seconds apart...
You can get the event and cancel it with the addEventListener like this:
document.addEventListener('dblclick', (event) => { 
event.preventDefault();  
event.stopPropagation(); 
}, true); // With this true, you are cancelling the dblclick event
let pendingClick;
function myclick(){
clearTimeout(pendingClick);
pendingClick = setTimeout(function (){
console.log('click');
}, 500);
}
function mydblclick(){
clearTimeout(pendingClick);
console.log('double click');
}
<div onclick="myclick()" ondblclick="mydblclick()">Double Click Me!</div>
Only work with the 'onclick' function to check if it was one or two clicks and use a variable to count the number of clicks in a given time interval.
Example:
var pendingClick;
var clicked = 0;
var time_dbclick = 500 // 500ms
function myclick(){
clicked++;
if(clicked >= 2){
mydblclick()
clearTimeout(pendingClick)
clicked = 0;
return;
}
clearTimeout(pendingClick)
pendingClick = setTimeout(() => {
console.log('One click!')
clicked = 0;
}, time_dbclick);
}
function mydblclick(){
console.log('double click');
}
<div onclick="myclick()">Double Click Me!</div>
Custom Events instead of inline event handlers
If one prefers to use .addEventListener and .removeEventListener instead of HTML inline-eventhandlers, I would suggest another approach based on Custom Events. That means one would not make use of the standard implementation of "click" and "dblclick", but create own event handling for both:
let lastLeftClick = document.dispatchEvent(new Event("click"));
let doubleclickLength = 300;
function leftClickHandler (e) {
if (e.button != 0) return; // only left clicks shall be handled;
let delaySinceLastClick = e.timeStamp - lastLeftClick.timeStamp;
let eIsDoubleClick = delaySinceLastClick < doubleclickLength;
if (eIsDoubleClick) {
let doubleclickEvt = new CustomEvent("doubleclick", e);
lastLeftClick = lastLeftClick = doubleclickEvt;
document.dispatchEvent(doubleclickEvt);
} else {
let singleClickEvt = new CustomEvent("singleclick", e);
lastLeftClick = singleClickEvt;
document.dispatchEvent(lastLeftClick);
}
}
// adding above click event implementation:
document.addEventListener("click", leftClickHandler);
using the new custom events:
document.addEventListener("singleclick", e=>console.log("single click"));
document.addEventListener("doubleclick", e=>console.log("double click"));

Single click and Double click on the same element, not working; Javascript

I am trying to add a click function that triggers when a button is clicked. I am also trying to figure out how to add a double click function onto the same element, that triggers a different event.
var click = false;
onEvent("image2", "click", function(event) {
click = true;
});
if (click === true) {
setTimeout(function() {
onEvent("image2", "click", function(event) {
setScreen("safeScreen");
console.log("double click");
});
}, 200);
} else {
onEvent("image2", "dblclick", function(event) {
setScreen("safeScreen");
console.log("click");
});
}
This code is completely wrong, but I don't know where to start/correct. What am I doing wrong? I am looking to have the single click not trigger when the user double clicks.
Update:
Try passing a function clicks() to your event listener like so:
onEvent("image2", "click", clicks);
Function clicks() will check if there was a single or double click based on setTimeout function. You can adjust setTimeout via timeout variable and of course you need clickCount variable declared outside clicks() function.
Pure js approach
Try adding two event listeners. Less code, much cleaner. Check this working example.
var selector = document.getElementById('codeorg');
selector.addEventListener('click', clicks);
// Global Scope variable we need this
var clickCount = 0;
// Our Timeout, modify it if you need
var timeout = 500;
// Copy this function and it should work
function clicks() {
// We modify clickCount variable here to check how many clicks there was
clickCount++;
if (clickCount == 1) {
setTimeout(function(){
if(clickCount == 1) {
console.log('singleClick');
// Single click code, or invoke a function
} else {
console.log('double click');
// Double click code, or invoke a function
}
clickCount = 0;
}, timeout || 300);
}
}
// Not important for your needs - pure JS stuff
var button = document.getElementById('button');
button.addEventListener('click', singleClick);
button.addEventListener('dblclick', doubleClick);
function singleClick() {
//console.log('single click');
}
function doubleClick() {
console.log('double click');
}
#codeorg {
margin-bottom: 100px;
}
<h2>Double Click</h2>
<button id="button">Click me</button>
<hr><hr>
<h2>Double click or Single Click</h2>
<button id="codeorg">Click me</button>

Press and hold button does not fire onClick

I'm having a problem with the button in my HTML5 application.
When I press the button a Video player runs and plays the video that is stored locally. My issue now is that when I hold the button and release it, it doesn't fire the video player. I'm using an onclick event on my button.
I want to achieve that if I press and hold the button and then release it, it fires the same event as the one I use with the onclick.
Use onmouseup event.
var button = //your button
button.onmouseup = function() {
//your logic
}
Actually onmousedown event instead of onClick will do the trick.
Again the same syntax:
Javascript
<button onmousedown ="clickFunction()">Click me!</button>
function clickFunction(){
//code goes here
}
jQuery
function clickFunction(){
$(button).onmousedown(function(){
//code goes here
});
};
you should use a boolean to save the current state.
var mouse_is_down = false;
var current_i = 0; // current_i is used to handle double click (to not act like a hold)
var button = document.querySelector("#myButton");
button.onmousedown = function(){
mouse_is_down = true;
// Do thing here for a mousedown event
setTimeout(
(function(index){
return function(){
if(mouse_is_down && current_i === index){
//do thing when hold
}
};
})(++current_i), 500); // time you want to hold before fire action in milliseconds
};
button.onmouseup = function(){
mouse_is_down = false;
current_i++;
// Do thing here for a mouseup event
};
Fiddle : link

Can I toggle popup after a click event with a mouseout event?

I'm using twitter bootstrap to display popovers with a click event. I'm requesting the info with the click event but I want to hide the popover after it looses focus so the user isn't required to click it again. Is this possible?
Basically I want to show the popover with a click event but then when the launch point looses focus from the mouse the popover is hidden.
Here is a link to the popover doc from twitter-bootstrap: http://twitter.github.com/bootstrap/javascript.html#popovers
This is what I'm currently doing:
jQuery:
$('.knownissue').on('click', function() {
var el = $(this);
if (el.data('showissue') == 'true') {
el.popover('toggle');
el.data('showissue', 'false');
return;
}
$.post('functions/get_known_issues.php', function(data) {
if (data.st) {
el.attr('data-content', data.issue);
el.popover('toggle');
el.data('showissue', 'true');
}
}, "json");
});
Any thoughts?
The following should work.
$('.knownissue').mouseleave(function() {
$(this).popover('hide');
});
Here is a custom jQuery event I call 'clickoutside'. It gets fired if and only if you click the mouse outside of the target element. It could easily be adapted for other event types (mousemove, keydown, etc). In your case, when fired it could close your modal.
(function ($) {
var count = 0;
$.fn.clickoutside = function (handler) {
// If the source element does not have an ID, give it one, so we can reference it
var self = $(this);
var id = self.attr('id');
if (id === '') {
id = 'clickoutside' + count++;
self.attr('id', id);
}
// Watch for the event everywhere
$('html').click(function (e) {
var source = $(e.target);
// ... but, stop it from propagating if it is inside the target
// element. The result being only events outside the target
// propagate to the top.
if (source.attr('id') == id || source.parents('#' + id).length > 0) {
return;
}
handler.call(this, e);
})
};
})(jQuery);
$('#targetElement').clickoutside(function(){
});
EDIT: Example JSFiddle.

Check if mouse is down on a mouseout event- jQuery

I want to know if a user stops pressing a button. So I capture the $button.mouseup(...) and $button.mouseout(...) events. However, I want the mouseout event to only matter when the user is still pressing the mouse- Otherwise, it will fire whenever the user passes over the button.
Any ideas?
Check e.which, which indicates the pressed button.
A quick and dirty method would be to use globals (or closures; some way of giving both the mouseup and the mouseout functions access to the same variable):
var mouseIsUp = true,
onMouseUp = function () {
mouseIsUp = true;
// ...
},
onMouseDown = function () {
mouseIsUp = false;
},
onMouseOut = function () {
if (!mouseIsUp) {
// ...
}
};

Categories