Jquery always repeat functions - javascript

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);
})

Related

When mouse stops moving in element in jQuery

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.

CSS fade out multiple times

I'm making a website which will let you update an SQL table, and I want to add some sort of feedback when a button is clicked. I have made an invisible button (opacity=0) which lies to the right of each row as a status. I made this JS fade() function to set the opacity to 1, then slowly bring it back to 0, so a message pops up then fades away.
function fade () {
var invis = document.getElementById("invis".concat(num.toString()));
if(invis.style.opacity > .990) {
invis.style.opacity = (invis.style.opacity) - .001;
setTimeout(fade, 50);
} else if(invis.style.opacity > 0) {
invis.style.opacity = (invis.style.opacity) - .05;
setTimeout(fade, 50);
}
}
The trouble is, since webpages are single-threaded, any other action will interrupt the animation and leave behind a half-faded status. So that's no good. So now I am trying to set up the invisible buttons to change class when a new row is updated. The new class looks like this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
This works fine, except it only works once. From here I cannot get the animation to play a second time. I have tried changing the class back to "invisible" then "invisible_anim" with no luck. I also can't use JQuery or Webkit. I'm wondering if there's some flag you can set for a button without actually clicking on it so I can reset the class when I need to? Or even some way to thread my JS function so I can stick with that.
If you would like to play the animation multiple times (see docs here: https://developer.mozilla.org/en-US/docs/Web/CSS/animation), if you would like to play it twice only.
so this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
would turn to
.invisible_anim {
...
opacity: 0;
animation:trans 3s 2 ;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
EDIT:
Apparently the requirements are different than what I thought. Instead the solution seems to be to key off the animation event located at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations and then when that animation done do what you need to do: so in JS-only
var e = document.getElementById("watchme");
e.addEventListener("animationend", listener, false);
function listener(){
//do what you need to do here
}
Just be careful, the reason for this is that most browsers have different "animationend" events that fire at different times. So definitely will need to be tested in different browsers to make sure that the animation event is firing at the right time. There's a post at (https://css-tricks.com/controlling-css-animations-transitions-javascript/) that details some of the issues you might encounter.
Have you considered using the CSS property "transition"? JavaScript has an event listener called "transitionend" that can trigger when your transition has ended, which you can use to reset the button.
First set the area for your alert button with the id invis.
CSS:
#invis {
opacity: 1;
transition: opacity 3s;
}
Then in JavaScript, generate your button and its content, which will appear at opacity 1, then transition to opacity 0. Your addEventListener will trigger when the animation is done, remove the button and reset the opacity for the next trigger.
JavaScript:
var invis = getElementByID("invis");
function fade() {
var button = document.createElement("button");
invis.appendChild(button);
invis.style.opacity = ("0");
invis.addEventListener("transitionend", function(){
invis.removeChild(button);
invis.style.opacity = ("1");
});
}
You can add the fade() function to your EventListener for the user "click."
This is my first time answering on StackOverflow, I hope this helps!
You need to start transparent then show then hide:
#keyframes trans {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
Then simply add your class (remove after the 3000ms time period)

How to change the button background image when music is paused

I am creating a simple audio player with HTML5 which has only one button. It is autoplay by default but is if the button is pressed it pauses and the other way round. The problem is I would like to to change the background image of the button whenever it is pressed.
Here is my code which obviously does nt change the bg.
var beepTwo = $("#musicBeat");
beepTwo[0].play();
$("#dan").click(function() {
if (beepTwo[0].paused == false) {
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
beepTwo[0].pause();
$(this).css("background","url (http://goo.gl/w5EWHg)");
});
} else {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
$(this).css("background","url (http://goo.gl/0GMoZK)");
}
});
DEMO
So is how can I change (toggle) the background image according to the button status. It must change by a fade effect.
Thanks in advance
this is referring to beepTwo when you're changing the background, not #dan. Add var self = this at the beginning of the click function and change this to self at the .css() function.
Use some simple CSS and take jQuery to add/remove them when necessary. The CSS transition property will give it a fade effect. Adjust the duration (0.5s) to what you want.
Also to note, you had to take $(this) outside of the animate in the first part of the if clause so it properly references #dan
JS:
$("#dan").click(function() {
if (beepTwo[0].paused == false) {
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
beepTwo[0].pause();
});
$(this).addClass("is-paused");
} else {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
$(this).removeClass("is-paused");
}
});
CSS:
.button.is-paused {
background-image:url(http://goo.gl/0GMoZK);
transition: background 0.5s ease;
}

Div flickers when mouse hovers over it

I have a div with a mouseout and a mouseover event which change the div's opacity.
But the div flickers if the you move the mouse over and out of the div in rapid succession.
I'm trying to find a way to stop the flickering so that it cancels the previous action and thus won't flicker.
I used a clear interval but doesn't seem to fix the problem... this is my fiddle:
http://jsfiddle.net/3xuyc/4/
My code code which clears interval for opacity transition:
function fade(dir){
var interId = null;
function fade_in() {
clearInterval(interId);
var div_id = document.getElementById('my_div');
var opacity = window.getComputedStyle(div_id).opacity;
interId = transition_opacity(div_id, opacity, 1, 0);
}
function fade_out() {
clearInterval(interId);
var div_id = document.getElementById('my_div');
var opacity = window.getComputedStyle(div_id).opacity;
interId = transition_opacity(div_id, opacity, 0,0);
}
if(dir){
fade_in();
} else {
fade_out();
}
}
var div_id = document.getElementById('my_div');
div_id.addEventListener('mouseover', function(){fade(1);}, false);
div_id.addEventListener('mouseout', function(){fade(0);}, false);
Any suggestions on how i can fix this problem?
If I understand correctly, you're using clearInterval to stop the previous fade in/out.
Try declaring var inter_id outside the fade() function. You're setting it to null each time you call fade().

Javascript slide effect onclick

I'd like to add a slide & fade effect to a DIV, with purely Javascript, using "onclick".
The code is here: http://jsfiddle.net/TCUd5/
The DIV that has to slide has id="pulldown_contents_wrapper".
This DIV is contained in a SPAN, that also triggers it:
<span onclick="toggleUpdatesPulldown(event, this, '4');" style="display: inline-block;" class="updates_pulldown" >
<div class="pulldown_contents_wrapper" id="pulldown_contents_wrapper">
And I think the JS code that controls the SPAN onclick is:
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.className= 'updates_pulldown_active';
showNotifications();
} else {
element.className='updates_pulldown';
}
}
If it is not possible to make it with pure JS, do you have an idea how could I do it with Mootools? (*I'd like to use only pure JS or the Mootols framework).
I have tried to implement the code from: why javascript onclick div slide not working? but with no results.
Thanks a lot.
I have managed to make it with Mootools, but I can't figure it out how to add a slide & fade effect, and a delay on mouseout
window.addEvent('domready', function() {
$('updates_pulldown').addEvents({
mouseenter: function(){
$('updates_pulldown').removeClass('updates_pulldown').addClass('updates_pulldown_active')
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
physics: 'pow:in:out',
transition: Fx.Transitions.Bounce.easeOut // This could have been also 'bounce:out'
}).show();
},
mouseleave: function(){
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
delay: 1000,
}).hide();
$('updates_pulldown').removeClass('updates_pulldown_active').addClass('updates_pulldown')
},
});
});
var toggleUpdatesPulldown = function(event, element, user_id) {
showNotifications();
}
Any idea?
jQuery is a lot easier, but with pure javascript you can do it.
In the CSS you'll need to use transitions
#thing { position:relative;
top: 0px;
opacity: 0.8;
-moz-transition: top 1s linear, opacity 1s linear;
-webkit-transition: top 1s linear, opacity 1s linear;
}
then in the javascript when you change the position of the element, it should change via the css transitions.
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.style.top = someValue; //something like '100px' will slide it down 100px
element.style.opacity = '1.0'; //will fade the content in from 0.8 opacity to 1.0
element.className= 'updates_pulldown_active';
showNotifications();
EDIT - provided jQuery code
call the jQuery library, most easily done from the google hosting
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
make the hover function
$(document).ready(function() {
$('.updates_pulldown').hover( //first function is mouseon, second is mouseout
function() {
$(this).animate({top: '50px'}).animate({opacity: '1.0'});
},
function() { //delay 1000 milliseconds, animate both position and opacity
$(this).delay(1000).animate({top: '0px'}).animate({opacity: '0.5'});
}
)
})
the function timing will be the same as whatever you set it to in the css with transition tags. using 'this' instead of the class name again makes sure that the effect only occurs on the specific instance of the class that is hovered over. im not sure if this animation is exactly what you were asking for, but if i understand the question correctly then the main functionality will work for you. just change the numbers and such to fit your needs.

Categories