Detect how long is mouse down - javascript

Can someone show me how to monitor how long the mouse is down, and on mouse up display that time in seconds?

I created a CodePen where you can time how long a <button> element is held down for. This is the relevant code:
HTML:
<button id="button">click</button>
JavaScript:
(function(window, document, undefined){
'use strict';
var start;
var end;
var delta;
var button = document.getElementById("button");
button.addEventListener("mousedown", function(){
start = new Date();
});
button.addEventListener("mouseup", function() {
end = new Date();
delta = (end - start) / 1000.0;
alert("Button held for " + delta + " seconds." )
});
})(window, document);
You probably don't want to use an alert in your application, but that is a good starting point. You should be able to insert the delta value into a DOM element without an issue.

Related

Javascript output not showing inside of a HTML p tag

I have a Javascript function which are doing the following functions,
Hide a div content when a button click.
Getting a input time (h:m:s) from a html input field and countdown them.
Showing the counting result in a html p tag.
function countdownTimeStart() {
/* hide the timer panel div when start button click*/
document.getElementById('timer_panel',).
innerHTML=document.getElementById('time_count').innerHTML;
/* Start count the time in timer panel */
/* Start count the time in timer panel */
var time = document.getElementById("picker-dates").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
var x = setInterval(function() {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
// add leading zero for seconds if seconds lower than 10
if (seconds < 10) {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "00:00:00";
}
}, 1000);
}
<div id="timer_panel" class="timer_panel1>
<input type = " text " id = "picker-dates ">
<button id="start " onclick="countdownTimeStart(); ">
</div>
<div id="time_count " class="time_count " style="visibility:hidden;>
<p id="demo" class="count"></p>
</div>
Problem is the time counting result not showing inside of the "demo" p tag when hiding timer panel div. How can I solve this, can anyone help me !
I've noticed a few mistakes in your code, I'll try to outline them as clearly as I can for you.
HTML
Firstly in your HTML you haven't closed your input tags. Also there was a typo on your div with the id time_count that didn't have closed quotations.
As some other people have mentioned, you also had a typo in your id name.
But the biggest thing, is that your p tag is wrapped in the div that inline you have set to visibility:hidden. Your JS doesn't address this. Once I moved the p tag out from this div, I was able to see an output.
However...
JavaScript
The Javascript code has some minor adjustments too. Why do you create a date object that you don't use? I'd delete this is you don't need it.
I would also suggest you store your element for use later, rather than calling document.getElementById('demo') everytime you use it, like so:
var el = document.getElementById('demo');
How to stop once the timer reaches 0
I've added this logic to your if else block
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval(x);
el.innerHTML = "00:00:00";
}
It uses code that you were trying to implement earlier but wasn't quite right. Moving it to here should do the trick. Check out the codepen where I have updated the code also.
Cancel the timer
Firstly you'll need to add a new button to your HTML
<button id="cancel">Cancel</button>
Then within your setInterval function I've added the following code:
// select cancel button
var cancel = document.getElementById('cancel');
// set up cancel functionality
// create a function to handle the cancel
function cancelCountdown(){
el.innerHTML = "00:00:00";
clearInterval(x);
}
// attach listener to cancel
// if cancel button is clicked
cancel.addEventListener( 'click', cancelCountdown);
Pause the timer
Okay, so we need to add another button to your HTML with a id of pause like so:
<button id="pause" >pause</button>
Then we add this pause functionality just below the code we put
in to clear the timer.
// select the pause button
var pause = document.getElementById('pause');
// create pause function
function pauseCountdown(){
// grab the current time
let pauseTime = hours+":"+minutes+":"+seconds;
// set that time into the timeInput
// so that next time 'Start' is pressed
// the paused time will be used
let timeInput = document.getElementById('picker-dates');
timeInput.value = pauseTime;
// stop the time to 'pause'
clearInterval(x);
}
// add listener to catch the pause
pause.addEventListener('click' , pauseCountdown);
How does it work? Well we're kinda cheating. You can't pause an Interval timer (that I've been able to find anyway) but you can take
the values you're using for the time and store them. Then when the start button is pressed, the timer will start again with the paused interval time as the countdown time. I hope that makes sense. Check out the codepen to see the example working.
Hope this helps!
Cheers,
Your p element has id demo1, but your code uses demo.

Fullcalendar js event overlap

I use fullcalendar js jquery plugin which is a great plugin but I have a small question do you know how:
I have a list of events which always not overlap.
Then sometimes I need to resize an event to be 1 or 2 hours much longer. The real step is here I try to make the next event to be not overlap but to move according to the resized end event. I have tried with event overlap custom function but it doesn't really work. There is always a gap of minutes between the two events.
I will send you a fiddle tomorrow to show you where I am.
/EDIT/
Just Create this Codepen :
http://codepen.io/cchumi/pen/pEGLXd
Javascript example for overlap :
eventOverlap: function(stillEvent, movingEvent) {
//Update MovingEvent
$('#calendar').fullCalendar('updateEvent', movingEvent);
//swap stillEvent time with movingEvent
stillEvent.end = stillEvent.end;
stillEvent.start = movingEvent.end;
//Update stillEvent
$('#calendar').fullCalendar('updateEvent', stillEvent);
//return true to allow swap.
return true;
}
it's been a while since your post but I think that I got a solution for you, I was looking your code and understood that, at the moment that the events overlaps the eventoverlap function is triggered, so I just add an event listener .mouseup() before your code to stop the trigger of your code until you release the click of the mouse. Now it works perfectly.
Now your code has to look like this:
eventOverlap: function(stillEvent, movingEvent) {
$('#calendar').mouseup(function() {
var movingEventEnd = moment(movingEvent.end).utc().format();
//"YYYY-MM-DDTHH:mm:ss"
var StillStart = moment(stillEvent.start).utc().format();
var StillEnd = moment(stillEvent.end).utc().format();
var duration = moment.duration(moment(StillEnd).diff(moment(StillStart)));
var hoursbaseStillEvent = duration.asHours();
console.log("Still Hours Base " + hoursbaseStillEvent);
$('#calendar').fullCalendar('updateEvent', movingEvent);
var movingEventNewEnd = moment(movingEvent.end).utc().format();
var durationMovingEvent =
moment.duration(moment(movingEventNewEnd).diff(moment(movingEventEnd)));
var hoursMovingEvent = durationMovingEvent.asHours();
console.log("hourss " + hoursMovingEvent);
stillEvent.start = moment(movingEvent.end).utc().format();
var StillEventStart = moment(stillEvent.start).utc().format();
console.log("StillEventStart " + StillEventStart);
var StillEventEnd = moment(stillEvent.end).utc().format();
var Startdate = moment(StillEventStart).utc().format();
console.log("Startdate " + moment(Startdate).utc().format());
var Enddate = moment(StillEventEnd);
var StillEventEndNew = moment(Startdate).add(hoursbaseStillEvent, 'hours');
console.log("StillEventEndNew " + moment(StillEventEndNew).utc().format());
stillEvent.end = moment(StillEventEndNew).utc().format();
$('#calendar').fullCalendar('updateEvent', stillEvent);
});
return true;
//return stillEvent.allDay && movingEvent.allDay;
},

How to seek with AudioContext

I would like to create buttons that will play next/prev song on click, but they should seek the music on long press.
I did manage to change songs, but I couldn't find the seek methods. Also how to make it play from beginning?
And is there a way to determine how much have passed since the beginning of the song? I found that buffer have duration, but no sing of actual play time.
At init:
context = new (window.AudioContext || window.webkitAudioContext)()
To play song:
var buffer = song.buffer
var source = context.createBufferSource()
source.buffer = song.buffer
source.connect(analysers.main)
source.start(0, offset || 0)
Guess, you should use AudioBufferNode (it has ability to do seek) - https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start
Also, this wrapper might be usefull - https://github.com/eipark/buffaudio
Use taphold API to acheive the long press Event.
$(function(){
$( "your element" ).bind( "taphold", tapholdHandler );
function tapholdHandler( event ){
/*write your code here for seek forward */
}
});
Use JQuery Timer
var mousedowntime;
var presstime;
$("button[id$='" + buttonID + "']").mousedown(function() {
var d = new Date();
mousedowntime = d.getTime();
});
$("button[id$='" + buttonID + "']").mouseup(function() {
var d = new Date();
presstime = d.getTime() - mousedowntime;
if (presstime > 999/*You can decide the time*/) {
//Do_Action_Long_Press_Event();
}
else {
//Do_Action_Click_Event();
}
});
To Play from Beginning
function beginAudio(){
audio.trigger('pause');
audio.prop("currentTime",audio.prop("currentTime")-audio.prop("currentTime"));
audio.trigger('play');
}
or set current time to zero and then play.
For Forward and Backward use this
audio.prop("currentTime",audio.prop("currentTime")-5);// 5 secs backward
audio.prop("currentTime",audio.prop("currentTime")+5);// 5 secs forward

Restart Game jQuery Function not working

I am using a jQuery Based Memory Game on my site. You can restart the game at anytime you like. Works great. Now I finish a game then I hit Play Again. If I hit restart it no longer works. Why and How do I fix it?
Here is a fiddle.
JS:
// this script shows how you can get info about the game
var game = jQuery('div.slashc-memory-game'); // get the game
var info = jQuery('p#info').find('span'); // get the info box
var restart = jQuery('a#restart').css('visibility', 'visible'); // get the play again link
var playAgain = jQuery('a#play-again').css('visibility', 'hidden'); // get the play again link
// format time like hh:mm:ss
var formatTime = function(s)
{
var h = parseInt(s / 3600), m = parseInt((s - h * 3600) / 60); s = s % 60;
return (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
}
// listen for game 'done' event
game.bind('done', function(e)
{
// show basic stats
var stats = game.slashcMemoryGame('getStats');
info.html('Success ! Number of clicks : ' + stats.numClicks + ', elapsed time : ' + formatTime(parseInt(stats.time / 1000)) + '.');
playAgain.css('visibility', 'visible'); // show link
restart.css('visibility', 'hidden'); // show link
});
// Restart action
restart.click(function(e)
{
game.slashcMemoryGame('restart'); // restart game
});
// play again action
playAgain.click(function(e)
{
playAgain.css('visibility', 'hidden'); // hide link
info.html('Memory Game, click to reveal images. <a id="restart" href="#">Restart</a>'); // reset text
game.slashcMemoryGame('restart'); // restart game
e.preventDefault();
});
HTML:
<p id="info"><span>Memory Game, click to reveal images. <a id="restart" href="#">Restart</a></span> <a id="play-again" href="#">Play Again</a></p>
You're replacing the #restart element whenever you click #play-again at this line:
info.html('Memory Game, click to reveal images. <a id="restart" href="#">Restart</a>');
This means the click handler for the #restart element is no longer attached to the new element.
You should attach the handler to an ancestor element which is always present in the DOM using a delegated event handler .on():
info.on('click', '#restart', function(e)
{
game.slashcMemoryGame('restart'); // restart game
});
Fiddle
I replaced the #restart element's directly-bound event handler with a delegated event handler. Here's the reference for an extra read: Direct and delegated events. Basically, you can only bind event handlers to elements currently in the DOM, and:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Calculating the time between two clicks in Javascript

I want to calculate the time between two clicks of an attribute with javascript but I don't know how.
For example;
click here
if the user clicks more than once -let's say in 5 seconds- I want to display an alert. I'm using jQuery if that helps. I don't know much about javascript but I've been coding a small project in my free time.
Something like this would do the trick. Keep a variable with the time of the last click and then compare it when the user clicks the link again. If the difference is < 5 seconds show the alert
<a id='testLink' href="#">click here</a>
<script type='text/javascript'>
var lastClick = 0;
$("#testLink").click(function() {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 5000) {
alert("LESS THAN 5 SECONDS!!!");
}
lastClick = t;
});
</script>
The following may help you getting started:
var lastClicked = 0;
function onClickCheck() {
var timeNow = (new Date()).getTime();
if (timeNow > (lastClicked + 5000)) {
// Execute the link action
}
else {
alert('Please wait at least 5 seconds between clicks!');
}
lastClicked = timeNow;
}
HTML:
click here
Create a variable to hold the time of a click, say lastClick.
Set up a click handler for the element you want to track clicks on.
Inside the handler, check for a value in lastClick. If there is no value, set it to the current time. If there is a value, compare it against the current time. If the difference is within the range you're checking for, display the alert.
Start with
var lastClicked = (new Date()).getTime(); //not zero

Categories