Reputation: 113
I'm trying run one animation and after go to other page with window.location.href, but I can't do it!
It run link with other page before that animation finish itself.
CSS:
#main {
position: absolute;
top: 0;
left: 415;
transition: 0.5s;
}
HTML
<button type="button" class="btn btn-secondary" onclick="backInit()">Back</button>
<div id="main">...</div>
I tried two ways:
$(document).ready( function() {
document.getElementById('main').style.left = 0;
} );
// Way 1
function backInit() {
setTimeout(run(), 2000);
setTimeout(returnInit(),2000);
}
// Way 2
function backInit() {
run().then( function() { window.location.href = baseURL + '/init.html'; } );
}
function run() {
document.getElementById('main').style.left = 415;
}
I need help with this!
Thanks!
Upvotes: 0
Views: 873
Reputation: 17943
You can try like following.
function run() {
console.log("Executing immediately(do your animation here)");
setTimeout(returnInit, 2000);
}
function returnInit() {
console.log("Executing after 2 seconds (do your navigation here)");
}
<button onclick="run()">Start</button>
Edit:
You should not call setTimeout
like following.
setTimeout(run(), 2000);
setTimeout(returnInit(),2000);
Otherwise it will execute the function immediately, you should change it like following.
setTimeout(run, 2000);
setTimeout(returnInit,2000);
Upvotes: 1
Reputation: 4003
You did not it add the animation so try this:
$(document).ready( function() {
document.getElementById('main').style.left = 0;
} );
// Way 1
function backInit() {
setTimeout(run(), 2000);
setTimeout(returnInit(),10000);
}
function run() {
var elem = document.getElementById("main");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 415) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
function returnInit() {
window.location.href ='https://stackoverflow.com/';
}
#main {
position: absolute;
top: 0;
left: 415;
animation-duration: 4s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" onclick="backInit()">Back</button>
<div id="main">...</div>
Upvotes: 1
Reputation: 24001
.animate()
in jquery and use its callback function to redirect This is how it can be done using jquery
$(document).ready( function() {
$('#main').css('left' , 0);
});
function run() {
$('#main').animate({'left' : 415} , 500 , function(){
window.location.href = 'https://www.google.com';
});
}
#main {
position: absolute;
top: 0;
background : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" onclick="run()">Back</button>
<div id="main">...</div>
Upvotes: 1