Im struggling to create a functionality which keeps on incrementing css property of an element when someone presses and 'holds' a button.
something like this:
var timeoutId = 0;
$('#left').mousedown(function() {
timeoutId = setTimeout(myFunction, 1000);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
function myFunction() {
var left = parseInt($("#menuElem").css('left')) + 10;
$("#menuElem").animate({
'left' : left + 'px'
});
}
I want that myFunction to be repeated again and again until mouseup or mouseleave event is fired.
cheers
According to this SO question you can't detect the current up or down state of a key, only monitor the respective events.
So you'd need something like this i guess
var mouseIsDown = false;
$('#button').mousedown(function(){
mouseIsDown = true;
incrementValue;
});
$('#button').mouseup(function(){
mouseIsDown = false;
});
Then have that function be all like:
function incrementValue() {
whatever++;
if(mouseIsDown){
setTimeout("incrementValue()", 20);
}
}
On mouse down, the mouseIsDown var gets set to true, and it starts a loop that continues to increment (at whatever interval you set the time parameter to in setTimeout()) until mouseIsDown is false, which happens on mouseup.
Related
I've toggled click event to a node and I want to toggle a dbclick event to it as well. However it only triggers the click event when I dbclick on it.
So How do I set both events at the same time?
You have to do your "own" doubleclick detection
Something like that could work:
var clickedOnce = false;
var timer;
$("#test").bind("click", function(){
if (clickedOnce) {
run_on_double_click();
} else {
timer = setTimeout(function() {
run_on_simple_click(parameter);
}, 150);
clickedOnce = true;
}
});
function run_on_simple_click(parameter) {
alert(parameter);
alert("simpleclick");
clickedOnce = false;
}
function run_on_double_click() {
clickedOnce = false;
clearTimeout(timer);
alert("doubleclick");
}
Here is a working JSFiddle
For more information about what delay you should use for your timer, have a look here : How to use both onclick and ondblclick on an element?
$("#test-id").bind("click dblclick", function(){alert("hello")});
Works for both click and dblclick
EDIT --
I think its not possible. I was trying something like this.
$("#test").bind({
dblclick: function(){alert("Hii")},
mousedown: function(){alert("hello")}
});
But its not possible to reach double click without going through single click. I tried mouse down but it does not give any solution.
I pretty much used the same logic as Jeremy D.
However, in my case, it was more neat to solve this thing with anonymous functions, and a little slower double click timeout:
dblclick_timer = false
.on("click", function(d) {
// if double click timer is active, this click is the double click
if ( dblclick_timer )
{
clearTimeout(dblclick_timer)
dblclick_timer = false
// double click code code comes here
console.log("double click fired")
}
// otherwise, what to do after single click (double click has timed out)
else dblclick_timer = setTimeout( function(){
dblclick_timer = false
// single click code code comes here
console.log("single click fired")
}, 250)
})
you need to track double click and if its not a double click perform click action.
Try this
<p id="demo"></p>
<button id='btn'>Click and DoubleClick</button>
<script>
var doubleclick =false;
var clicktimeoutid = 0;
var dblclicktimeoutid = 0;
var clickcheck = function(e){
if(!clicktimeoutid)
clicktimeoutid = setTimeout(function(){
if(!doubleclick)
performclick(e);
clicktimeoutid =0;
},300);
}
var performclick =function(e){
document.getElementById("demo").innerHTML += 'click';
}
var performdblclick = function(e)
{
doubleclick = true;
document.getElementById("demo").innerHTML += 'dblclick';
dblclicktimeoutid = setTimeout(function(){doubleclick = false},800);
};
document.getElementById("btn").ondblclick = performdblclick;
document.getElementById("btn").onclick=clickcheck;
</script>
a slightly different approach - The actual click comparison happens later in the timeOut function, after a preset interval... till then we simply keep tab on the flags.
& with some simple modifications (click-counter instead of flags) it can also be extended to any number of rapid successive clicks (triple click, et al), limited by practicality.
var clicked = false,
dblClicked = false,
clickTimer;
function onClick(param){
console.log('Node clicked. param - ',param);
};
function onDoubleClick(param){
console.log('Node Double clicked. param - ',param);
};
function clickCheck(param){
if (!clicked){
clicked = true;
clickTimer = setTimeout(function(){
if(dblClicked){
onDoubleClick(param);
}
else if(clicked){
onClick(param);
}
clicked = false;
dblClicked = false;
clearTimeout(clickTimer);
},150);
} else {
dblClicked = true;
}
};
Is it possible to use Javascript/jQuery to check to see if your cursor is hovering over the top 20 pixels or so of the webpage?
Example:
Similar to how the exit bar works on windows 8. You have to hover at
the top of the screen for a second or so for the close minimize
options to appear.
I wondered if this is possible to replicate purely with Javascript/jQuery, to then allow a jQuery.fadeIn() or jQuery.slideDown() to take place.
Hopefully it's possible!
Sure, with a mouse event and checking if e.pageY is less than 20px, you're mouse is in the top 20 pixels etc.
var isOnTop = false;
$(window).on('mousemove', function(e) {
isOnTop = e.pageY < 20;
});
I'll add a few examples, keeping the mouse still at the top for a second will trigger the event
$(window).on('mousemove', function(e) {
clearTimeout($(this).data('timer'));
if ( e.pageY < 20 ) {
$(this).data('timer',
setTimeout(function() {
$('#top').slideDown()
}, 1000)
);
}
});
$('#top').on('mouseleave', function() {
$(this).slideUp();
});
FIDDLE
Any movement at the top requires a little more code, and another variable to keep from removing the timer
$(window).on('mousemove', function(e) {
if ( e.pageY < 20 ) {
if ( ! $(this).data('isSet') ) {
$(this).data('timer',
setTimeout(function() {
$('#top').slideDown()
$(this).data('isSet', false);
}, 1000)
).data('isSet', true);
}
} else {
clearTimeout($(this).data('timer'));
$(this).data('isSet', false);
}
});
$('#top').on('mouseleave', function() {
$(this).slideUp();
});
FIDDLE
You should add a mousemove listener to body. Also, you should create a boolean flag (variable or .data(). In that listener you check if the mouse is in the top x px of the page, and set the flag to that boolean value.
If the flag changed by that operation, either
setTimeout for showing something, if the flag changed to true.
clearTimeout said timeout and hide the thing of shown, if the flag changed to false.
I believe you'll be able to implement this based on my answer. I'll be happy to give more instructions, but I'm not going to give you copypastible JS code.
Pseudocode:
flag = false
when mouse moved over page {
if mouse y < value and flag = false {
flag = true
show after 1 second
}
if mouse y > value and flag = true {
flag = false
cancel showing
hide if shown
}
}
I have some code where I have a timer. Every 3 seconds the background changes colors, and when you hover the stop button, the color changer pauses, I have an onclick event that i am using in junction with the mouseout event but the mouseout event cancels out my onclick event. What can I do so that the onclic event works still after I move the mouse from the stop button?
Code: jsfiddle
<script>
var colors = new Array();
colors[0] = "green";
colors[1] = "blue";
colors[2] = "gray";
var i = 0;
var timer;
function changeOfPlans() {
timer = setInterval("colorChange()", 3000);
}
function colorChange() {
document.getElementById("one").style.backgroundColor = colors[i];
document.getElementById("two").style.backgroundColor = colors[i];
i++;
if (i == 3 || i > 3) {
//start over by setting i to 0
i = 0;
}
}
function stop() {
clearTimeout(timer);
}
</script>
You need to update the on click action so that it sets a variable. Then have the mouse out first check whether that variable is set before restarting the color changing. Demo.
I modified your JavaScript like so:
var stopped = false;
function changeOfPlans() {
if (!stopped) {
timer = setInterval("colorChange()",3000);
}
}
function fullstop() {
stopped = true;
stop();
}
Then I updated your onclick to call fullstop() instead of just stop(). Since I left the other stop() function the same, the hover-to-stop-move-away-to-restart functionality still works as you had it originally. All of the other JavaScript remains the same.
<button type="button" onmouseover="stop()" onmouseout="changeOfPlans()" onclick="fullstop()">Stop</button>
There are other ways of doing this -- enhzflep suggests a good one in the comments -- but this is the simplest.
You are using setInterval, so to cancel you need clearInterval not clearTimeout.
Also don't run it again on mouseout i guess:
onmouseout="changeOfPlans()"
Basically I need some code to execute when the mouse is clicked and being dragged around. With my current code the code executes when the mouse is down and when the mouse is moved but then when the mouse click is released the code continues to execute so I have included an if statement. I'm sure there is a much more efficient way of doing this so any help would be really appreciated :)
P.S another problem I am having is say the user clicks on the element, then lets go the mouseup ("//more code") gets executed once but if the user then clicks again and lets go it will be executed twice and if they select and deselect again 3 times etc.
As you can probably tell I am a bit of a jQuery noob! :P
Current code:
$('element').mousedown(function(event){
mouseDown = true;
$(document).mousemove(function(event2){
if(mouseDown){
//code goes here
}
}).mouseup(function(){
mouseDown = false;
//more code
});
});
"Another problem I am having is say the user clicks on the element,
then lets go the mouseup ("//more code") gets executed once but if the
user then clicks again and lets go it will be executed twice and if
they select and deselect again 3 times etc."
That's because you're binding an event every time they press the mouse down; the first time it happens, you have one event handler. The next time, two event handlers. The third time, three event handlers. And so on. You'll want to call unbind() beforehand to remove the existing event handlers, then rebind them.
I have recently used the following code to create a draggable jquery extension. You can pass a target for the drag action.
(function ($) {
var element;
var target;
var settings = {
onDrop: function (x, y) { }
};
var methods = {
init: function (options) {
if (options) {
$.extend(settings, options);
}
return this.each(function () {
// Code here for each element found by the selector
element = $(this);
if (options.target) {
target = $(options.target);
}
else {
target = element;
}
// Move the element by the amount of change in the mouse position
element.parent().mousedown(function (event) {
element.data('mouseMove', true);
element.data('mouseX', event.clientX);
element.data('mouseY', event.clientY);
});
element.parents(':last').mouseup(function () {
element.data('mouseMove', false);
});
element.mouseout(methods.move);
element.mousemove(methods.move);
});
},
move: function (event) {
if (element.data('mouseMove')) {
var changeX = event.clientX - element.data('mouseX');
var changeY = event.clientY - element.data('mouseY');
var newX = parseInt(target.css('margin-left')) + changeX;
var newY = parseInt(target.css('margin-top')) + changeY;
target.css({ 'margin-left': newX, 'margin-top': newY });
settings.onDrop(newX, newY);
element.data('mouseX', event.clientX);
element.data('mouseY', event.clientY);
}
}
};
$.fn.draggable = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.draggable');
return null;
}
};
})(jQuery);
then call it like this:
$('#overlay').draggable({ target: "#imagebehide", onDrop: function (x, y) {
$('#leftpos').val(x);
$('#toppos').val(y);
} });
I need to do the following. As soon as the user clicks on a div, i want to save the mouse coordinations while the user is moving the cursor over the div and is holding the left mouse button. When the user leaves the div or releases the left button, i want to stop recording the coordinates. I've got the following code:
$(document).ready(function() {
var coordhdl = new coordinateHandler();
$("#test").mousedown(function(e) {
$("#test").mousemove(function(ee) {
$("#test").mouseup(function(e) {
stopIt = true;
});
if(stopIt == false)
{
coordhdl.addCords(ee.pageX - this.offsetLeft, ee.pageY - this.offsetTop);
}
});
});
});
The problems with this code are:
It records coordinate even when the user only clicked the div without pressing the left button.
It doesn't stop recording the coordinates once it has been clicked.
I am new to Javascript/jQuery, so I don't know very much about it.
Something like this should work. It sets a flag to true/false when the mouse is pressed/released respectively. When the mouse moves, if the flag is set, the coordinates are added:
$(document).ready(function() {
var isDown = false,
coordhdl = new coordinateHandler();
$("#test").mousedown(function() {
isDown = true;
}).mouseup(function() {
isDown = false;
}).mousemove(function(e) {
if(isDown) {
coordhdl.addCords(ee.pageX - this.offsetLeft, ee.pageY - this.offsetTop);
}
});
});
Here's a demo of something similar in action (it simply writes the coordinates to a p element instead of using your coordinateHandler object).
Don't attach the event handlers inside the event handlers. On every mouse move you attach a new mouseup event handler. They don't get overridden, they get appended.
Use a "global" flag instead:
$(document).ready(function() {
var coordhdl = new coordinateHandler(),
recording = false;
$("#test").mousedown(function(e) {
recording = true;
}).mousemove(function(e) {
if(recording) {
coordhdl.addCords(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
}
}).mouseup(function(e) {
recording = false;
});
});
Every time there is a mousedown event, you add a mousemove handler, and every time the mouse moves, you add another mouseup handler. I can't see where the stopIt variable is declared so the scope of this variable may also be an issue. You don't need to nest the handlers, so try it this way.
$(document).ready(function() {
var coordhdl = new coordinateHandler();
var isRecording = false;
$("#test").mousedown(function(e) { isRecording = true })
.mouseup(function(e) { isRecording = false })
.mousemove(function(ee) {
if(isRecording)
{
coordhdl.addCords(ee.pageX - this.offsetLeft, ee.pageY - this.offsetTop);
}
});
});