Click and Hold Event Listener with JavaScript

listen to mouse hold event on website?

If you want the hold state then it will be the state when you are in mousedown event state for a while. This state exists when you press mousedown but not mouseup. Hence you need to take a variable which records the current state of the event.

JS

$('div').on('mousedown mouseup', function mouseState(e) {
if (e.type == "mousedown") {
//code triggers on hold
console.log("hold");
}
});

Working Fiddle

Click and Hold event listener with Javascript

You can use Javascript's setTimeout function and bind it to mousedown events. Have a look at the snippet below:

// click and hold event listener
var timeout_id = 0, hold_time = 1000, hold_menu = $('.hold_menu'), hold_trigger = $('.hold_trigger');
hold_menu.hide();
hold_trigger.mousedown(function() { timeout_id = setTimeout(menu_toggle, hold_time);}).bind('mouseup mouseleave', function() { clearTimeout(timeout_id);});
function menu_toggle() { hold_menu.toggle();}
ul.hold_menu {  list-style: none;  padding: 0;  margin: 0;}
ul.hold_menu a, div.hold_trigger { display: inline-block; padding: 5px 15px; border: 1px solid #ccc; width: 300px;}
ul.hold_menu a:link, ul.hold_menu a:visited { color: black; text-decoration: none;}
ul.hold_menu a:active, ul.hold_menu a:hover { background: #ff0; text-decoration: none;}
div.hold_trigger { color: black; cursor: pointer;}
div.hold_trigger:hover { background: #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hold_trigger">Click and hold to toggle the menu</div><ul class="hold_menu"> <li><a href="#">Option 1</a></li> <li><a href="#">Option 2</a></li> <li><a href="#">Option 3</a></li></ul>

Detect Hold Mouse-Click in Javascript

The problem here is that your code runs as a blocking loop.

while(mouseDown){
console.log("mouse is still down");
rad++;
console.log(rad)
}

The browser evaluates Javascript in a single thread and this loop will never pause to let the browser process those event handlers.

Instead you can use just use asynchronous functions to listen for mousedown events, then start a timer. If the mouse is still down when the timer finishes, then you can count it as a long click.

var mouseIsDown = false;

window.addEventListener('mousedown', function() {
mouseIsDown = true;
setTimeout(function() {
if(mouseIsDown) {
// mouse was held down for > 2 seconds
}
}, 2000);
});

window.addEventListener('mouseup', function() {
mouseIsDown = false;
});

These asynchronous actions (addEventListener, setTimeout) won't block the main thread.

Hold event with javascript

(function() {
var mouseTimer; function mouseDown() { mouseUp(); mouseTimer = window.setTimeout(execMouseDown,2000); //set timeout to fire in 2 seconds when the user presses mouse button down }
function mouseUp() { if (mouseTimer) window.clearTimeout(mouseTimer); //cancel timer when mouse button is released div.style.backgroundColor = "#FFFFFF"; }
function execMouseDown() { div.style.backgroundColor = "#CFCF00"; }
var div = document.getElementById("bam"); div.addEventListener("mousedown", mouseDown); document.body.addEventListener("mouseup", mouseUp); //listen for mouse up event on body, not just the element you originally clicked on }());
#bam { width:100px; height: 100px; border: 1px solid black; }
<div id="bam"> Hold mouse button for 2 seconds. </div><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p><p>Bacon</p>

Click and hold event Javascript

Please try this

I have created a DEMO . This is what I understood from your question. If this is not what you meant please add some html or code you have tried so that its easy to understand your problem.

$(document).ready(function(){
$("img").mouseup(function(){
$("#containment-wrapper").css("background-color", "black");
});
$("img").mousedown(function(){
$("#containment-wrapper").css("background-color", "white");
});
});

Touchscreen Press & Hold

UPDATED

for not fully functioanlity I edited the code and also changed the logic

I come up with variable timerValue which increases in every 0.1s when mouse is pressed and when that timerValue reaches 2, button changes color to orange and on 5 changes on red and prints triggered as well

and on mouseup which will be called after user picks up finger from mouse, timerValue backs to 0 and resets also button class

interval is variable where are I store setInterval function and on mouse release I clear it

I included also paragpraph tag where is shown the timer to understand how it works

const btn = document.querySelector(".btn")
const timer = document.querySelector("p") //can be deleted

let timerValue = 0
let interval;

const mousePress = () => {
interval = setInterval(() => {
timerValue++
timer.innerHTML = timerValue //can be deleted

if(timerValue === 2) btn.classList.toggle("orange")
if(timerValue === 5) {
btn.classList.toggle("red")
console.log("triggered")
}
}, 100)
}

const mouseRelease = () => {
clearInterval(interval)
timerValue = 0
timer.innerHTML = timerValue //can be deleted
btn.className = "btn"
}

btn.addEventListener("mousedown", mousePress)
btn.addEventListener("mouseup", mouseRelease)
.btn.orange{
color: orange;
}
.btn.red{
color: red;
}
<button class="btn">Click</button>
<p></p>

Why OnMouseDown Event occur once , how to handle mouse hold event

mouseup and mousedown are not supposed to continuously fire. They are meant to signal a single action has happened.

However, you could achieve this effect with a custom timer (setInterval() to be more specific) that is triggered on mousedown and cancelled on mouseup:

document.getElementById("main");

var timer = null; // Variable to hold a reference to the timer

// Set up an event handler for mousedown
main.addEventListener("mousedown", function(evt){
// Start a timer that fires a function at 50 millisecond intervals
timer = setInterval(function(){
// the function can do whatever you need it to
console.log("Mouse is down!");
}, 50);
});

// Set up a custom mouseup event handler for letting go
// of the mouse inside the box or when mouse leaves the box.
function mouseDone(evt){
clearInterval(timer); // Cancel the previously initiated timer function
console.log("Mouse is up or outside of box!"); // And, do whatever else you need to
}

// Bind the handlers:
main.addEventListener("mouseup", mouseDone);
main.addEventListener("mouseleave", mouseDone);
#main {
background-color:yellow;
width: 300px;
height: 100px;
}
<div id="main">Press and hold the mouse down inside me!</div>

How can I listen for a click-and-hold in jQuery?

var timeoutId = 0;

$('#myElement').on('mousedown', function() {
timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});

Edit: correction per AndyE...thanks!

Edit 2: using bind now for two events with same handler per gnarf

How to do eventListener by holding right click using VANILLA JS

The MouseEvent API (with its mousedown and mouseup events) lets us check the event.button property to learn which mouse button the user is activating. And we can keep track of how much time passes between mousedown and mouseup to decide what to do when the mouse button is released, such as running a custom showOrHideDiv function.

And the contextmenu event fires after a right-click (unless the relevant context menu is already visible, I guess.) We can suppress the default contextmenu behavior if necessary -- although this power should be used sparingly if at all.

Note that the technique used here is problematic in that it assumes the user will never use their keyboard to see the context menu, which will eventually cause accessibility snafus and other unpleasant surprises for users. This is why hijacking the default right-click behavior should be avoided if possible (maybe in favor of something like Shift + right-click) unless the user explictly opts in to the new behavior.

// Defines constants and adds main (`mousedown`) listener
const
div = document.querySelector("#item"),
RIGHT = 2,
DELAY = 150;
document.addEventListener('mousedown', forceDelay);

// Main listener sets subsequent listeners
function forceDelay(event){

// Right mouse button must be down to proceed
if(event.button != RIGHT){ return; }

// Enables contextmenu and disables custom response
document.removeEventListener('contextmenu', suppressContextMenu);
document.removeEventListener('mouseup', showOrHideDiv);

// After 150ms, disables contextmenu and enables custom response
setTimeout(
function(){
document.addEventListener('contextmenu', suppressContextMenu);
document.addEventListener('mouseup', showOrHideDiv);
},
DELAY
);
}

// The `contextmenu` event listener
function suppressContextMenu(event){
event.preventDefault();
}

// The `mouseup` event listener
function showOrHideDiv(event){
if(event.button != RIGHT){ return; }
const
x = event.clientX,
y = event.clientY;
div.classList.toggle('d-none'); // classList API includes `toggle`
div.style.transform = `translate(calc(${x}px - 50%), calc(${y}px - 50%))`;
}
#item{ position: absolute; top: 0; left: 0; width: 100px; height: 100px; background: royalblue; }
.d-none{ display: none; }
<div id="item" class="d-none"></div>


Related Topics



Leave a reply



Submit