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!
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);
.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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.