When mouse stops moving in element in jQuery - javascript

What I'm trying to achieve: when my mouse is moving then do this, but when it stops moving for like half a second then do that, but when it starts to move again then do that.
This is my temporary jQuery:
$(document).ready(function() {
$('.test').mouseenter(function(){
$(this).mousemove(function(){
$(this).css({
'background-color' : '#666',
'cursor' : 'none'
});
});
});
$('.test').mouseout(function(){
$(this).css({
'background-color' : '#777',
'cursor' : 'default'
});
});
});
And I have absolutely no idea how to do that, basically my code does this: when you enter an element with a mouse and your mouse is moving inside that element then apply this CSS and when your mouse leaves the element then apply this CSS, but when mouse is inside that element and it stops moving for some period of time then do this <- I can't figure the last bit out.

I understood that you want to detect the mouse movements over a particular element.
To achieve this, you need to use the mousemove event... There is no mousefroze event, sadly!
So you will use a setTimeout() and will constantly clear its callback while the mouse moves. Since that event fires multiple times on a single slight movement, you can set the delay quite tight. So it should be accurate.
The setTimeout callback will execute only when the mouse will stop moving. And that is the whole "trick".
About delays... I think that 100 ms is the lowest accurate value. Less than that will create flickering on "slow" user moves.
The mouseenter is not really usefull here, because it is overridden by the mousemove event right after (because when the mouse enters... it also moves!). But the mouseleave or mouseout is really usefull to restore the element's original state and clear the timeout too... Because the mouse won't be moving over your element does'nt mean it doesn't move at all. So you have to clear that when leaving.
$(document).ready(function() {
var test = $('#test');
var moveTimer;
test.on("mouseout",function(){
$(this).css({
'background-color' : 'white',
}).text("");
clearTimeout(moveTimer);
});
test.on("mousemove",function(){
console.log("I'm moving!");
clearTimeout(moveTimer);
moveTimer = setTimeout(function(){
console.log("I stopped moving!");
test.css({
'background-color' : 'red',
}).text("The mouse is not moving.");
},100)
$(this).css({
'background-color' : 'blue',
}).text("Movement detected...");
});
});
#test{
margin:50px;
border:2px solid black;
height:200px;
width:200px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
CodePen

Sounds like you're looking for timeouts. In a similar project, I used something like this:
var timer;
function active() {
// Apply active styles
}
function inactive() {
// Apply inactive styles
}
$('.test').mousemove(function(){
active(); // Apply active styles
clearTimeout(timer); // Reset the timer
timer = setTimeout(out, 500);
});
Once you move the mouse over the area, that launches a timer that resets every mouse move. If the timer is ever allowed to expire, the user's gone inactive and we run whatever code we like.

So I was just googling. This is the answer:
$(document).ready(function() {
var countdown;
$('.test').hover(function() {
setTimeout(function(){
$('.test').css({
'background-color' : '#666',
'cursor' : 'none'
});
cursor();
}, 2000);
}, function(e){
$('.test').css({
'background-color' : '#777',
'cursor' : 'default'
});
});
$('.test').mousemove(function() {
$('.test').css({
'background-color' : '#777',
'cursor' : 'default'
});
cursor();
});
function cursor() {
countdown = setTimeout(function() {
$('.test').css({
'background-color' : '#666',
'cursor' : 'none'
});
}, 2000);
}
});
});

This may deviate from your current code, but I think CSS is more appropriate here than JavaScript.
.test {
background-color:#666;
}
.test:hover {
background-color:#777;
cursor:none;
}
These lines of CSS should perform the exact same thing without the complication. Note that in your example, for every pixel the mouse moves, the css is set once more. And since you are not removing the event handler on mouse out, the event is actually ran multiple times.

Related

Animate tooltip on user hover with jQuery

Im trying to make my tooltip bounce onmouse hover,
I have the following that works with sporadic results, as in the the tooltip bounces fast for 3 seconrds ro so, then slow for 3 seconds etc... I also need to stop this function on mouseout, Can somebody see where im going wrong to get the variation in bounce speed?
// Tooltip title
$('.male').mouseover(function(e) {
var tiptitle = $(this).find('.highlight');
setInterval(function(){
tiptitle.animate({top:'-85px'}, 100, function() {
tiptitle.animate({top:'-75px'}, 100);
});
},200);
}).mouseout(function() {
});
if you choose to go the route of the effects plugin bounce effect use this code , then use stop() on mouseout
$('.male').mouseover(function(e) {
var tiptitle = $(this).find('.highlight');
tiptitle.effect("bounce", { times:3 }, 300);
}).mouseout(function() {
$(this).find('.highlight').stop();
});
otherwise , I believe you are getting sporadic speeds of bounce because of -85px and -75px both at 100

Jquery always repeat functions

I have these 2 functions to create opacity effect
<script>
function trans(id)
{
$(".pris_"+id).stop().fadeOut(1000);
$(".pris_"+id).css({ opacity: 0.1});
stop();
}
function trans_reverse(id)
{
$(".pris_"+id).stop().fadeIn(1000);
$(".pris_"+id).css({ opacity: 0.8});
stop();
}
</script>
<div id="productos_image_soon" class="pris_1" onmouseover="trans('1');"onmouseout="trans_reverse('1');">
Product in a few time
</div>
Into the div i call each function , the problem is when i put mouseover the div all time and in recursive mode the second function execute and after the first function and continue executed , the effect is when mouseover the opacity low and when mouseout opacity grow
Working ..... here jsfiddle.net/dSesq/
I donĀ“t know why this happens, I've tried the stop() function but the problem continues
It makes no sense why you are setting the opacity of the element after fading it in. Use fadeTo!
function trans(id, opacity) {
$(".pris_"+id).stop().fadeTo( 1000, opacity);
}
And you should probably use mouseenter and mouseleave. Also you are going to get weird results having the mouse over an element that is going to disappear.
Your code could be written as
$(".trigger").on("mouseover mouseout", function(evt){
var opacity = evt.type=="mouseover" ? 1 : .8;
$(this).stop().fadeTo(1000, opacity);
})

Issue with jquery fadein

I have a piece of code here which it works but not sure why my fadein and fadeout doesn't work for the body,
If you think what the issue i'm having please let me know thanks
<script type="text/javascript">
$(window).load(function() {
var lastSlide = "";
$('#slider').nivoSlider({
effect: 'random',
directionNavHide : true,
slices : 15,
animSpeed : 500,
pauseTime : 6000,
controlNav : false,
pauseOnHover : true,
directionNav:true, //Next & Prev
directionNavHide:true, //Only show on hover
beforeChange: function(){
if(lastSlide == "images/header_used.jpg") { //use the bg image of the slide that comes before the newslide
$("body").attr("style","background: #000 url(images/bg.jpg) top center no-repeat;").fadeIn("slow");
} else {
$("body").attr("style","background: #ADADAD url(images/bgnd_grad.jpg) repeat-x;").fadeOut("slow");
}
},
afterChange: function() {
t = $(this).children("a:visible");
lastSlide = $("img", t).attr("src");
}
});
});
</script>
While it may solve your mission with the body background. i would instead have used addClass and removeClass. You are manipulating the style attribute which also show/hide uses it.
I have no way to test it but what happens if you switch the fades to show() and hide(), just to determine if delay is a factor.. :)
It my come by the fact that "lastSlide" variable could store multiple object (the one from img and the one from visible link).
t = $(this).children("a:visible");
lastSlide = $("img", t).attr("src"); //could store multiple source.
This make comparation a little bit tricker and could create bug.
Plus the fact that you use the worst way to style your body. As other says, use class or .css jQuery function (http://api.jquery.com/css/).
Hope this help
fadein and fadeout work for body,absolutely.
as Reflective said, it should be
$("body").css("background","#000 url(images/bg.jpg) top center no-repeat;").fadeOut("slow")
if still doesn't work, you may should look into your nivoSlider function

How to manage multiple elements in a mouseenter function in Mootools?

Hi! I really try to find a topic related to my issue here, but I had no luck...
Some simple code: I have two divs, placed in the same position -
<div id="fader1" style="display:inline-block;position:absolute;background-image:url(images/fader1.png);opacity:1;width:296px;height:435px;margin:-215px 50px -20px"></div>
<div id="fader2" style="display:inline-block;position:absolute;background-image:url(images/fader2.png);opacity:0;width:296px;height:425px;margin:-215px 50px -20px"></div>
The idea is when the mouse passes over the div "fader1", the opacity changes to 0, and the opacity of fader2 changes to 1. And turn back like the beginning if I put the cursor out of the div.
I've tried to achieve this with mootools but I'm now in a dead-end.
Mootools Demos have the example of Fx.Morph like this:
$('myElement').set('opacity', 0.5).addEvents({
mouseenter: function(){
// This morphes the opacity and backgroundColor
this.morph({
'opacity': 0.6,
'background-color': '#E79D35'
});
},
mouseleave: function(){
// Morphes back to the original style
this.morph({
opacity: 0.5,
backgroundColor: color
});
}
});
As you can see, I can only manage ONE element (this.morph). I try to put other element like: "('fader1').morph" with no results... But I think that I'm doing it wrong.
I really appreciate any help you can give me to achieve this in mootools. Regards!
you should read the manual and not copy/paste from examples.
$('myElement').set('opacity', 0.5).addEvents({
mouseenter: function(){
// This morphes the opacity and backgroundColor
this.morph({
'opacity': 0.6,
'background-color': '#E79D35'
});
}
});
in the above function, the scope this refers to myElement. if you need to reference a different element, then simply do so.
(function(){
var other = $('myOtherElement').set('moprh', {
link: 'cancel'
}); // save a reference and set link to cancel existing morphing
$('myElement').set('opacity', 0.5).addEvents({
mouseenter: function(){
// This morphes the opacity and backgroundColor
other.morph({
'opacity': 0.6,
'background-color': '#E79D35'
});
},
mouseleave: function(){
// Morphes back to the original style
other.morph({
opacity: 0.5,
backgroundColor: color
});
}
});
}());
read up on what $ (documentid) returns (an element), saving an element into a variable and referencing it later - this is standard javascript.

Mouseover event handler brings up both divs when I want only one

I am trying to do a mouseover event for one picture where when you mouseover a div comes up and animates on the picture. When I do my mouseover though, it brings up both divs for separate pictures when I only want one at a time. Here is my code. The first part is the mouseover. Second is mouseout.
$('.portfolio img').mouseover(function(){
$(this).css('cursor', 'pointer');
$(this).parent().find('img:first').stop().animate({opacity:1}, 800, function() {
$("div.folio").animate({ height: '+=25px', top: '-=24px' }, 100, function() {
$("div.folio span").animate({ opacity: 1 }, 500);
});
});
});
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 800, function() {
$("div.folio span").animate({ opacity: 0 }, 500, function() {
$("div.folio").animate({ height: '-=25px', top: '+=24px' }, 100);
$("div.folio").css('top', '-9px');
});
});
});
<div class="portfolio">
<h2>The Portfolio</h2>
<p class="slideTwo">Check out some of our recent projects.</p>
<ul>
<li><img src="portfolioOne.jpg"></img><div class="folio"><span>thesite.com</span></div></li>
<li><img src="portfolioOne.jpg"></img><div class="folio"><span>mysite.com</span></div></li>
</ul>
</div>
Using jQuery's $("div.folio") will return all divs with a class of "folio". Since you are seeing this animation on both images, rather than just the one you've moused-over, I'm assuming they both have the same class on the div they want to animate. In order to only animate one, you'll need to be more specific when selecting it with jQuery. Including $(this) on the path to the div to animate usually works, but I can't tell you the exact code without the corresponding HTML.
You need to cancel the bubble up event by returning "false" from your event handler.
$('.portfolio img').mouseover(function(){
// Your logic here...
return false;
});
There are a couple of concerns that I have about this which may or may not be problematic depending on what else is going on that you haven't shown.
You're doing $(this).parent().find('img:first') inside of a jQuery onmouseover function where $(this) should already be representing the img that you care about. Did you find that was necessary for some reason?
You could be more specific in your selector. Try doing $(".portfolio>ul>li>img")
img_grayscale is only mentioned once in your markup in your question so I'm not sure how that class gets applied but I'm assuming it does.
You could just add the class portfolio (or some unique identifier) to your images directly and probably have an easier time figuring out exactly why it isn't working as you expect. Then your mouseover selector could just be $(".specialClass")
You should definitely try posting a jsfiddle.net; you could borrow any two images off the web for testing.
Managed to figure this one out. I had to basically transverse the DOM through the following code. I referenced the image and then I went to the parent then to the next element in the DOM which was my div of div.folio. Then I went to the child of that object to fade it in. I did the same thing in reverse basically on the mouseout.
$('.portfolio img').mouseover(function(){
$(this).css('cursor', 'pointer');
$(this).parent().find('img:first').stop().animate({opacity:1}, 800, function() {
$(this).parent().next().animate({ height: '+=25px' }, 100, function() {
$(this).children().animate({ opacity: 1 }, 100);
});
});
});
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 800, function() {
$(this).parent().next().children().animate({ opacity: 0 }, 100, function() {
$(this).parent().animate({height: '-=25px' }, 100);
});
});
});

Categories