toggle the mousemove mousestop event - javascript

My question is simple. When my mouse moves, I would like to execute a function which would print "you are moving" in a div tag. When my mouse is not moving, I would like the text function to go away.
Below is a pseudo code that i can think of. So for example, the text function will be called every 50/1000 of a second and check if the mouse is moving. if it is moving, the text will show. if the mouse is not moving, the text will not show. How can i achieve this since there is no mousestop event?
$(function() { setInterval(text, 50);
});
function text() {
/*Do something to check if mouse is moving*/
/*if mouse is moving*/
if{
$("#shu").text("You are moving");
} else {
$("#shu").remove();
}
}

Pure javascript solution:
var shu = document.getElementById("shu");
var timeout;
document.addEventListener("mousemove", function() {
shu.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
shu.innerHTML = "";
}
jsFiddle

You can use jQuery .mousemove function along with set interval to check the mouse movement.
Here is an example code.
var lastTimeMouseMoved = "";
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$(".text").show();
lastTimeMouseMoved = new Date().getTime();
var t=setTimeout(function(){
var currentTime = new Date().getTime();
if(currentTime - lastTimeMouseMoved > 1000){
$('.text').fadeOut('fast');
}
},1000)
});
});
body{
background-color:#333;
}
.text{
display:none;
color:white;
font-size:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Your are moving!!</div>

$(window).mousemove(
function() {
$("#shu").text("You are moving");
}, function() {
$("#shu").remove();
}
);

With jquery
var lastMove = new Date().getTime() ,currentTime;
$(window).mousemove(function(){
lastMove = new Date().getTime();
});
setInterval(function(){
currentTime = new Date().getTime();
if(currentTime - lastMove > 400)
$("#shu").empty();
else
$("#shu").text("moving");
},20);

function mouseStop(callback) {
$(window).mousemove((function() {
var t;
return function() {
if(typeof t !='undefined')
clearTimeout(t); //we should check that `t` is not null
t = setTimeout(function() {
callback();
}, 200)//change to 200 so it will not trigger on mouse move
}
})())
}
mouseStop(function() {
console.log("stop!!!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Issues with making images draggable

I am currently creating my own website. I need code to allow users to change the position of some images by dragging them. I have written this HTML, CSS and JS in separate files.
The whole click and drag think works, when I click on the image and drag it on any side, it moves.
When I release the mouse button nothing happens. I have tried break and return, but they don't stop the function. Do you have any suggestions?
PS: I'm only a beginner in JS, so if you have any other advice about my code, go for it!
class img {
constructor(id, left, top) {
this.id = "#" + id;
this.left = parseInt(left, 10);
this.top = parseInt(top, 10);
};
};
$(".draggable").on("mousedown", function detectClick(focus) {
var stop = false;
var clickPos = [focus.pageX, focus.pageY];
var selected = new img($(this).attr('id'), $(this).css("left"), $(this).css("top"));
console.log(clickPos, selected);
$(selected.id).on("mousemove", function startMvt(move) {
var newPos = [move.pageX, move.pageY];
console.log(newPos);
$(selected.id).css("top", selected.top + newPos[1] - clickPos[1]);
$(selected.id).css("left", selected.left + newPos[0] - clickPos[0]);
$(selected.id).on("mouseup", function stop() {
var stop = true
console.log("stopped moving!");
return;
});
if (stop) {
return false;
};
});
if (stop) {
return false;
};
}).delay(5);
.draggable {
position: relative;
}
#img_1 {
top: 10%;
left: 20%;
z-index: 1;
cursor: move;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="draggable" id="img_1" draggable="false" src="content/medium_im_test.jpg">
$(".draggable").on("mousedown",
you are only calling a function on the event of mousedown, you need a corresponding mouseup event handler.
how about adding
.mouseup(function(){
alert('up');
});
at the end or .delay(5);
like
$(".draggable").on("mousedown", function detectClick(focus) {
var stop = false;
var clickPos = [focus.pageX, focus.pageY];
var selected = new img($(this).attr('id'), $(this).css("left"), $(this).css("top"));
console.log(clickPos, selected);
$(selected.id).on("mousemove", function startMvt(move) {
var newPos = [move.pageX, move.pageY];
console.log(newPos);
$(selected.id).css("top", selected.top + newPos[1] - clickPos[1]);
$(selected.id).css("left", selected.left + newPos[0] - clickPos[0]);
$(selected.id).on("mouseup", function stop() {
var stop = true
console.log("stopped moving!");
return;
});
if (stop) {
return false;
};
});
if (stop) {
return false;
};
}).delay(5).mouseup(function(){
alert('up');
});
it worked for me!! I am also a beginner js programmer! so I don't fully understand your code, but I think you have to do something where I put alert('up')

Stop timeout when user click and hold the picture

I have a gallery, that will show pictures to user for 5 to 5 seconds.
function slideSwitch() {
var current = $('#slideshow .active');
current.removeClass('active');
if (current.next().length) {
current.next().addClass('active');
myInterval = setTimeout(slideSwitch, 5000);
bar();
}
}
http://jsfiddle.net/6hcste51/
I'd like to pause the timeout when user click and hold the click on div holder.
For example, the timeout is in 3 seconds, if user click and hold the holder div I'd like to stop in 3 seconds until the hold ends, and then go to 4 and 5 seconds to call the function again.
I saw this function but I don't know how to add it in my slideSwitch(). any ideas?
selector.addEventListener('mousedown', function(event) {
// simulating hold event
setTimeout(function() {
// You are now in a `hold` state, you can do whatever you like!
}, 500);
}
you need to set timer function it can support pause and resume
need to set anmatin can support pause and resume and reset (i use jquery queue &
animations)
At last the code will be :
jsfiddle Link
//--------------------------global variables----------------
var isfirst= true;
var cycle_remaining = null;
var anim_time = 5000;//in mil sec
var downtime = null;
var myTimer = null;
var is_down = false;//is down event
var is_SpeedClick_getnext = false;//set to true you want to set click to get next image
//---------------------------timer-------------------------
function Timer(callback, delay) {
var timerId, start, remaining = delay;
cycle_remaining = remaining;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
cycle_remaining = remaining;
};
this.resume = function() {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
cycle_remaining = remaining;
};
this.resume();
}
function slideSwitch() {
var current = $('#slideshow .active');
if (current.next().length) {
current.removeClass('active');
current.next().addClass('active');
myTimer = new Timer(slideSwitch, 5000);
resetanim();
startanim();
}
}
//--------------------- mouse control functions----------------------
$(document).on( "click", ".holder", function() {
if(isfirst){
isfirst = false;
slideSwitch();
}
});
$('.holder').on('mouseout mouseup', function(e) {
if(is_down && !isfirst){
is_down = false;
//set this if if you want to set click to get next image
if(downtime > new Date() - 100 && is_SpeedClick_getnext){
slideSwitch();
}else{
myTimer.resume();
startanim();
}
}
});
$(".holder").mousedown(function() {
if(!isfirst){
downtime = new Date();
is_down = true;
myTimer.pause();
puseanim();
}
});
//--------------------- animation control functions----------------------
//start or resume animation
function startanim() {
var myDiv = $( ".bottom_status" );
myDiv.show( "slow" );
myDiv.animate({
width:"100%"
},cycle_remaining );
myDiv.queue(function() {
var that = $( this );
//that.addClass( "newcolor" );
that.dequeue();
});
}
function rutanim() {
var myDiv = $( ".bottom_status" );
myDiv.show( "slow" );
myDiv.animate({
width:"100%"
}, anim_time );
myDiv.queue(function() {
var that = $( this );
//that.addClass( "newcolor" );
that.dequeue();
});
}
//to puse animation
function puseanim() {
var myDiv = $( ".bottom_status" );
myDiv.clearQueue();
myDiv.stop();
}
// to reset animation
function resetanim() {
var myDiv = $( ".bottom_status" );
myDiv.animate({
width:"1%"
}, 200 );
myDiv.queue(function() {
var that = $( this );
that.dequeue();
});
}
.holder{
display:none;
}
.active{
display:block;
}
.bottom_status{
position:absolute;
bottom:0;
background:blue;
width:0%;
height:10px;
left: 0;
margin-left: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id=slideshow>
<div class='holder active'>
Click here to start counting and click and hold to stop.
</div>
<div class='holder'>
text 2
</div>
<div class='holder'>
text 3
</div>
<div class='holder'>
text 4
</div>
</div>
<div class=bottom_status></div>
There is a Var called is_SpeedClick_getnext set to true you want to set click to get next
Note : the explanation in code comment
As mentioned you cant pause a setTimeout, but I have a solution which I think you might find useful.
I've created a second timer function that effectively stores the remaining time before a slide in the #slideshow element as an attribute every 500ms. If the user clicks on an image then it will cancel the original setTimeout and pauses the changing of the #slideshow attribute until the mouseup event. After the mouseup event is fired a new setTimeout is started using the remaining time stored in the attribute.
I also added a line of code to restart from the first image at the end of the slideshow (not sure if that's what you planned).
Hope this helps
// Start slider
slideSwitch();
// Start independent timer
timer();
function slideSwitch() {
// Select active slide and remove active status
var current = $('#slideshow .active');
current.removeClass('active');
// Check if there is a 'next' element and give active class, or return to first
if (current.next().length) {
current.next().addClass('active');
} else {
$("#slideshow img").first().addClass("active");
}
// Reset timer for the slide, store time and reset timer stop
myInterval = setTimeout(slideSwitch, 3000);
$("#slideshow").attr("time", "3000");
$("#slideshow").attr("timeStop", "false");
}
function timer() {
// Check if the slide countdown has been stopped
if ($("#slideshow").attr("timeStop") != "true") {
// Get last saved time and reduce by 500ms
tempTime = parseInt($("#slideshow").attr("time") - 500);
// Save time to slideshow attribute
$("#slideshow").attr("time", tempTime)
// Show countdown on label
$("#timerLabel").text(tempTime);
}
// Continue timer
myTimer = setTimeout(timer, 500);
}
// Add event for mousedown which cancels timer
$("#slideshow img").mousedown(function() {
// Stop timer and clear countdown for slide
$("#slideshow").attr("timeStop", "true");
window.clearTimeout(myInterval);
});
// Start timer on mouse up
$("#slideshow img").mouseup(function() {
// Restart a new countdown for slide using stored time remaining value
tempTime = parseInt($("#slideshow").attr("time"));
myInterval = setTimeout(slideSwitch, tempTime);
$("#slideshow").attr("timeStop", "false");
});
img {
display: none;
border: 5px solid black;
}
img.active {
display: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slideshow" time="">
<img src="https://via.placeholder.com/150/fff">
<img src="https://via.placeholder.com/150/000" class="active">
<img src="https://via.placeholder.com/150/f00">
<img src="https://via.placeholder.com/150/0f0">
<img src="https://via.placeholder.com/150/00f">
</div>
<p>Remaining: <span id="timerLabel"></span> ms</p>

Autostart jQuery slider

I'm using a script that animates on click left or right to the next div. It currently works fine but I'm looking to add two features to it. I need it to repeat back to the first slide if it is clicked passed the last slide and go to the last slide if click back from the first slide. Also, I'm interested in getting this to autostart on page load.
I've tried wrapping the clicks in a function and setting a setTimeout but it didn't seem to work. The animation is currently using CSS.
Here's the current JS:
<script>
jQuery(document).ready(function() {
var boxes = jQuery(".box").get(),
current = 0;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)){
} else {
current--;
updateBoxes();
}
console.log(-boxes.length + 1);
console.log(current);
});
jQuery('.left').click(function () {
if (current === 0){
} else{
current++;
updateBoxes();
}
});
function updateBoxes() {
for (var i = current; i < (boxes.length + current); i++) {
boxes[i - current].style.left = (i * 100 + 50) + "%";
}
}
});
</script>
Let me know if I need a jsfiddle for a better representation. So far, I think the code is pretty straightforward to animate on click.
Thanks.
Try
jQuery(document).ready(function () {
var boxes = jQuery(".box").get(),
current = 0,
timer;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)) {
current = 0;
} else {
current--;
}
updateBoxes();
}).click(); //initialize the view
jQuery('.left').click(function () {
if (current === 0) {
current = -boxes.length + 1;
} else {
current++;
}
updateBoxes();
});
function updateBoxes() {
//custom implementation for testing
console.log('show', current)
$(boxes).hide().eq(-current).show();
autoPlay();
}
function autoPlay() {
clearTimeout(timer);
//auto play
timer = setTimeout(function () {
jQuery('.right').click();
}, 2500)
}
});
Demo: Fiddle
Here's an example based on my comment (mostly pseudocode):
$(function(){
var boxes = $('.box'),
current = 0,
timer;
// Handler responsible for animation, either from clicking or Interval
function animation(direction){
if (direction === 1) {
// Set animation properties to animate forward
} else {
// Set animation properties to animate backwards
}
if (current === 0 || current === boxes.length) {
// Adjust for first/last
}
// Handle animation here
}
// Sets/Clears interval
// Useful if you want to reset the timer when a user clicks forward/back (or "pause")
function setAutoSlider(set, duration) {
var dur = duration || 2000;
if (set === 1) {
timer = setInterval(function(){
animation(1);
}, dur);
} else {
clearInterval(timer)
}
}
// Bind click events on arrows
// We use jQuery's event binding to pass the data 0 or 1 to our handler
$('.right').on('click', 1, function(e){animation(e.data)});
$('.left').on('click', 0, function(e){animation(e.data)});
// Kick off animated slider
setAutoSlider(1, 2000);
Have fun! If you have any questions, feel free to ask!

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Show Div on Mouseover after three second

I want on first click it will show after 3 seconds but after the first click when I clicked it will shown before 3 seconds:
function Func1()
{
document.getElementById('div1').style.visibility = "visible" ;
}
function Func1Delay()
{
setTimeout("Func1()", 3000);
}
function Func2Delay()
{
document.getElementById('div1').style.visibility = "hidden" ;
}
Your English or description is very poor, but from what I understand, you want something like this :
var div = document.getElementById('div1'),t;
function changeStyle(element,prop,value){
element.style[prop] = value;
}
function showDiv(){
changeStyle(div,'opacity','1');
}
function hideDiv(){
changeStyle(div,'opacity','0');
}
div.addEventListener('mouseover',function(){
t = setTimeout(showDiv,3000);
},false);
div.addEventListener('mouseout',function(){
clearTimeout(t);
hideDiv();
},false);​
Here's a demo : http://jsfiddle.net/gion_13/TSVA5/
You have to hover the "invisible" div and it will show after 3 seconds.
this works for me
the markup:
<input type="button" value="clickme" onmouseout="ClearIntv()" onmouseover="DelayShow('showMe',5000)" />
<div id="showMe" style="display:none;background-color:red;width:50px;height:50px;">
</div>
the script:
var intv;
function DelayShow(timeOutMs) {
var elm = document.getElementById("showMe");
var now = new Date().getTime();
var end = now + timeOutMs;;
intv = setInterval(function () {
now = new Date().getTime();
if (now >= end) {
elm.style.display = "block";
clearInterval(intv);
}
}, 500);
}
function ClearIntv() {
clearInterval(intv);
}
Activates the counter on MouseOver, and cancels on MouseOut

Categories