I want to stop setInterval() when left margin is 1200px.
My code is :-
<html>
<body>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
$('#btn').click(function () {
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
if (a == "1200px") {
clearInterval(i);
}
}, 50);
});
});
</script>
<img src="48_800[1].jpg" height="50px" width="50px"><br>
<input type="button" value="start" id="btn"><br>
</body>
</html>
It is not working.Can anyone help me?
You should cast to an integer the pixels value a = parseInt(a);. (as before you were obtaining values of margin-left with decimals, such as 99.45px and then 199.45px so it was jumping the 100px)
Live example
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
a = parseInt(a);
if (a >= 100) {
clearInterval(i);
}
}, 50);
Update
I've just noticed the animation still running after the interval has been cleared. Not sure why is this happening but I found a way to solve the problem by caching the final margin in a variable rather than calculating it inside the animation.
Live example 2
Note that in the examples I'm using >=100 to see the results.
Use this instead: Updated
$(document).ready(function () {
$('#btn').click(function () {
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
//console.log(a.substring(0,a.lastIndexOf('px')));
if (a.substring(0,a.lastIndexOf('px')) >= 1200) {
clearInterval(i);
}
}, 50);
});
});
try this:
if(parseInt(a) >= 1200)
{
clearInterval(i);
}
},50);
$(document).ready(function () {
$('#btn').click(function () {
var a="";
while(a != "1200px"){
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
a = $('img').css('margin-left');
}
});
});
your existing code looks erroneous ,besides referring to SetInterval is not required, the same could be achieved with decent while clause itself.
happy Coding :)
try to change the value for the time into the setInterval method
the number value must to be in milliseconds
Related
I would like to alternate the contents of a div (or swap in a new div if better) every few seconds, with a fade in/out. Jquery prefered, or pure js fine too.
Based on Arun's solution, I have added the Jquery below, and it works perfectly... but how do I make it repeat?
HTML:
<div class="wrapper" style="height:100px">
<div id="quote1">I am a quote</div>
<div id="quote2">I am another quote</div>
<div id="quote3">I am yet another quote</div>
</div>
Javascript: (as per Arun in the comments)
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
$els.eq(++i % len).fadeIn();
})
}, 2500)
})
Try
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
Demo: Fiddle
Here is a working example:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
this sounds like a job for...a slider. There are a ton of jQuery plugin options out there,
I've always been a fan of Malsup
jQuery plugins by malsup
he even has responsive ones ready to go. Google "jQuery slider" to be overwhelmed with options.
Use a slider plugin there are lots on the internet. This is a simple snippet I wrote that works with any number of elements without having to change the javascript.
It's very easy to change.
http://jsfiddle.net/Ux9cD/39/
var count = 0;
$('.wrapper div').css('opacity', '0');
var varName = setInterval(function() {
//hide all the divs or set opacity to 0
$('.wrapper div').css('opacity', '0');
//get length
var length = $('.wrapper div').length;
//get first child:
var start = $('.wrapper div').eq(count);
if (count < length) {
animateThis(start,length,count);
count++;
} else {
console.log('end of list');
//restore back to hidden
//set count back to 0
$('.wrapper div').css('opacity', '0');
count = 0;
}
}, 2000);
varName;
function animateThis(start,length,count)
{
$( start ).animate({
opacity: 1
}, 1000, "linear", function() {
//return count++;
});
}
This will do it if you set your second and third divs to hidden:
window.setInterval(function(){
window.setTimeout(function(){
$('#quote1').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 0);
window.setTimeout(function(){
$('#quote2').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 3000);
window.setTimeout(function(){
$('#quote3').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 6000);
}, 3000);
It's not going to do exactly what you want because fading takes time, so two divs will be onscreen at the same time. I tried to remedy this by having them fadeIn() slowly and fadeOut() quickly, but I'd recommend taking out the fading altogether and just hiding them.
See demo.
Also, #ArunPJohny has a solution here that is a bit difficult to understand but does get rid of the fading delay problem. Alternatively, here's my no-fading solution.
HTML
<div id="div1">quote 1</div>
<div id="div2" style="display:none">quote 2</div>
JavaScript
i=0;
setInterval(function(){
if(i%2 == 0)
$('#div1').fadeOut('slow', function(){
$('#div2').fadeIn('slow')
})
else
$('#div2').fadeOut('slow', function(){
$('#div1').fadeIn('slow')
})
i++;
}, 2000)
Fiddle
Here is something you can try if you can do without fade in and fadeout. Just a simple few lines of java script no need to add any plugins etc.
Also look at this link Jquery delay it has sample with delay and fade in fadeout. May be you can tailor it to your needs.
Try in your browser
<html>
<head>
<script type="text/javascript">
function swapDiv(){
var firstString = document.getElementById("quote1").innerHTML;
var secondString = document.getElementById("quote2").innerHTML;
document.getElementById("quote1").innerHTML = secondString;
document.getElementById("quote2").innerHTML = firstString;
setTimeout(swapDiv, 3000);
}
setTimeout(swapDiv, 3000);
</script>
</head>
<body>
<div id="quote1">I am another quote</div><span>
<div id="quote2">I am yet another quote</div><span>
</body>
</html>
I'm using Jquery Collision to detect two objects overlapping each other. Here is a JSFiddle of the problem.
(apologies for including jquery collision script in HTML, couldn't find other way)
Click anywhere in the gray container to move the green div over the white div.
HTML Structure:
<div class="container">
<div class="test"></div>
<div class="menu"></div>
</div>
JS:
$(document).ready(function () {
var hit_list;
$(".container").click(function () {
$(".menu").stop().animate({
left: "+=100px"
}, 300, function () {
$(".menu").animate({
left: "0"
}, 800);
});
//Test for collision
hit_list = $(".menu").collision(".test");
if (hit_list.length != 0) {
alert("welcome Earthling!");
}
});
});
The problem with my method is that, it doesn't detect collision every time. Even though it passes over the white division fine, the alert isn't displayed everytime.
Am I going wrong anywhere in checking for collision? Is there a better/more efficient method to detect collisions during animation ?
jQuery animate has a step callback (https://api.jquery.com/animate/), it gets executed after each step of the animation.
Use it like this:
$(document).ready(function () {
var hit_list;
$(".container").click(function () {
$(".menu").stop().animate({
left: "+=100px"
}, {
duration: 300,
complete: function () {
$(".menu").animate({
left: "0"
}, 800);
},
step: function(){
//Test for collision
hit_list = $(".menu").collision(".test");
if (hit_list.length != 0) {
alert("welcome Earthling!");
}
}
});
});
});
Try this http://jsfiddle.net/aamir/y7PEp/6/
$(document).ready(function () {
var hit_list;
var hits=0;
$(".container").click(function () {
var $this = $(this);
function checkCollision() {
//Test for collision
hit_list = $(".menu").collision(".test");
if (hit_list.length != 0) {
hits++;
$(".menu").html(hits+ ' hits');
}
}
$(".menu").stop().animate({
left: "100px"
}, 300, function () {
checkCollision();
$(".menu").animate({
left: "0"
}, 800);
});
});
});
I am able to move button to left side but after that how i can again move it to right side.
Can i also use delay here.
Here is the code that i have tried:
$(document).ready(function () {
example_animate(10);
});
function example_animate(px) {
$('#Button1').animate({
'marginLeft': px
});
}
you can use this, it is working perfectly for me, it will continuously move your element back and forth, and you can also vary animation speed.
function animatethis(targetElement, speed) {
$(targetElement).animate({ marginLeft: "+=10px" },
{
duration: speed,
complete: function () {
targetElement.animate({ marginLeft: "-=10px" },
{
duration: speed,
complete: function () {
animatethis(targetElement, speed);
}
});
}
)};
}
use this to implement:
animatethis($('#controlid'), 1500);
Cannot answer properly without looking at your HTML and CSS but what you are doing is right. Simply call your example_animate() with a negative value
i.e.
example_animate(-10);
Or if you want to bring it to the original value (assuming originally it had 0 margin)
example_animate(0);
Note: This is probably not the best way to animate
Yes, the animate function takes a function that is called after the animation is complete. So you can do:
$(document).ready(function () {
example_animate(100);
});
function example_animate(px) {
$('#Button1').animate({
'marginLeft': px
}, function(){
$('#Button1').animate({
'marginLeft': 1
});
});
}
http://jsbin.com/ixajol/1/edit
Do execly the same only to the right, Its not that hard if you can make it go left.
Maybe
var button_init_marginLeft;
$(document).ready(function () {
button_init_marginLeft = $('#Button1').css("marginLeft");
example_animate(10, true);
example_animate(null, false);
});
function example_animate(px, to_left) {
if (to_left)
{
$('#Button1').animate({
'marginLeft': px
});
}
else
{
$('#Button1').animate({
'marginLeft': button_init_marginLeft
});
}
}
?
Is it possible to trigger a function mid way through an animation?
The animation includes a solid block which swipes over an image from top to bottom - I would like to trigger a function at the point that the image is completely covered and remove the image from the html (mid way through the animation)
My current function is -
function animateCover() {
$('#cover').animate({ bottom: '1400px'}, 4000, function() { });
}
The image is completely covered at 800px point - can I access this property to trigger a function?
since there isn't a tick counter in jQuery, you need to "emulate" it:
function animateCover() {
var
$cover = $('#cover'),
interval = setInterval(function(){
if ($cover.is(':animated')){
if (parseInt($cover.css('bottom')) > 800){
alert('trigger');
clearInterval(interval);
}
} else {
clearInterval(interval);
}
}, 13); // 13 is the minimum possible in Javascript
$cover.animate({ bottom: '1400px'}, 4000, function() { $cover.text('done'); });
}
jsFiddle: http://jsfiddle.net/emV4p/1/
What about splitting the animation into 2.
function animateCover() {
$('#cover').animate({ bottom: '700px'}, 2000, function() {
$('#imgID').hide();
$('#cover').animate({ bottom: '1400px'}, 2000 );
});
}
Updated: Here's a perfectly working solution with minimal code-
WORKING DEMO
jQuery-
$(document).ready(function(){
setInterval(function(){
$("#image").css('background-image','none');
},2000);
$("#block").animate({
bottom:'400px'
},3000);
});
I am trying to make a div bounce every 4 seconds and after 15 seconds fadeOut. The code bellow makes the div disappear and the bounce doesn't happen.
$(document).ready(function(){
function salta() {
$('.recomenda').effect("bounce",{ times:4 },300);
}
setInterval(salta, 4000);
$('.recomenda').delay(15000).fadeout('slow');
});
This isn't doing the job, any hint you can give me?
Kind regards.
With the help of Matt i figured how to do it:
function salta() {
$('.recomenda').effect("bounce",{ times:4 },300);
}
var interval = setInterval(salta, 3500);
setTimeout(function (){
clearInterval(interval);
$('.recomenda').fadeOut('slow');
}, 15000);
Edit - final version
$(document).ready(function ()
{
var $recomenda = $('.recomenda');
function salta()
{
$recomenda.effect('bounce', {times:4}, 300);
}
salta();
var interval = setInterval(salta, 4000);
setTimeout(function ()
{
// stop the interval from running unnecessarily
clearInterval(interval);
$recomenda.fadeOut('slow');
}, 15000);
});
There were 2 other problems:
fadeout() instead of fadeOut()
Using .delay() was interfering with the bounce effect
Demo: http://jsfiddle.net/mattball/a2F3W/