Jquery code to show loading before display the main content - javascript

I am working with jquery on my page, I want when ever user click on a button an image will show loading for 1 second before the main content appears
Here is my code:
<script>
$(document).ready(function(){
$("#UseractivityLog").click(function(){
$(".UserProfileLogs-cont").html("<img src='image/loading.gif'/>");
//Then for 1/2 seconds this UserProfileLogs will display
$(".UserProfileLogs").toggle();
});
$("#IdealLog").click(function(){
$(".UserProfileLogs-con").toggle();
});
});
</script>
Here is my HTML part
Logs
<div id="UserProfileLogs-cont">
<div id="IdealLog"></div>
<div id="UserProfileLogs"></div>
</div>
Please i will appreciate jsfiled sample

You have some selector inconstancies, make sure you are watching those (# instead of .).
For the pause, use setTimout():
$(document).ready(function(){
$("#UseractivityLog").click(function(){
$("#UserProfileLogs-cont").html("Loading...");
setTimeout(function() {
$("#UserProfileLogs-cont").html("<img src='http://placehold.it/350x150'>");
}, 1000);
//Then for 1/2 seconds this UserProfileLogs will display
$(".UserProfileLogs").toggle();
});
$("#IdealLog").click(function(){
$("#UserProfileLogs-cont").toggle();
});
});
Fiddle: https://jsfiddle.net/Lqgum8hu/
For your comment:
//Then for 1/2 seconds this UserProfileLogs will display
Use another timeout:
setTimeout(function() {
// Whatever...
}, 500);
I changed your HTML a little to present the examples, but it can be changed to however you want it without changing the Javascript.

You can use setTimeout to update the image source after n seconds.
Also you can achieve this using single div and an nested img without using separate container for loading icon and image.
Hope this below snippet will be useful
HTML
Logs
<div id="UserProfileLogs-cont">
<img src="">
</div>
JS
$(document).ready(function(){
var _gif = "http://assets.motherjones.com/interactives/projects/features/koch-network/shell19/img/loading.gif";
var _forest="http://www.discovertheforest.org/images/hero/home/6.jpg";
$("#UseractivityLog").click(function(){
$("#UserProfileLogs-cont img").attr("src",_gif);
setTimeout(function(){
$("#UserProfileLogs-cont img").attr("src",_forest);
},3000)
});
});
Check this jsfiddle

You can wait until the body is ready:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
background-color: rgba(192, 192, 192, 0.5);
background-image: url("http://i.stack.imgur.com/MnyxU.gif");
background-repeat: no-repeat;
background-position: center;
}
Here is a JSFiddle that demonstrates this technique.

Related

Set delays - Javascript

Currently I have a simple fire animation. It just show two flames tongues in same place and show hide within 0.3s. Right now I want set delays. After few milliseconds, stop the loop and start again like that. I tried with javascript setInterval but it's continuously running.
var $wrapper = $('.wrapper');
setInterval(function() {
$wrapper.toggleClass("alt");
}, 300);
.wrapper {
text-align: center;
position: relative;
}
.flames,
.wrapper-img,
.show-1,
.show-2 {
position: absolute;
}
.flames {
display: none;
}
.flame-1 {
left: 38px;
top: 32px;
}
.flame-2 {
left: 67px;
top: 40px;
}
.flame-2 img {
top: 220px;
}
.wrapper-img {
top: 220px;
}
.wrapper .flame-1 {
display: block;
}
.wrapper .flame-2 {
display: none;
}
.wrapper.alt .flame-1 {
display: none;
}
.wrapper.alt .flame-2 {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="flame-1 flames">
<img src="https://i.imgur.com/0Pfsrdh.png" alt="">
</div>
<div class="flame-2 flames">
<img src="https://i.imgur.com/EypytyC.png" alt="">
</div>
<div class="wrapper-img">
<img src="https://i.imgur.com/moNtPwG.png" class="wrap-img" alt="">
</div>
</div>
Any solution? Jsfiddle
As far as I see you need soething like this
var $wrapper = $('.wrapper');
function flamebaby(){
$wrapper.toggleClass("alt");
setTimeout(function() {
$wrapper.toggleClass("alt");
setTimeout(function() {
flamebaby();
},600)
}, 200);
}
flamebaby();
https://jsfiddle.net/uy43w5qq/7/
You are probably looking for CSS keyframe animations which will let you run keyframe based transitions/animations without the need of JavaScript. This will also ensure that the browser can do optimizations for your animations, they will probably run smoother.
JS based answers are already provided so I'm not going in there except for a small sidenote on setInterval.
Using setInterval() is not recommended since the body function theoretically may take longer than the interval causing a stackoverflow. A better way is to use setTimeout to call a function, which at the end of executions schedules a new timeout for itself.
const foo = () => {
console.log('bar');
setTimeout(foo, 300);
}
setTimeout(foo, 300);
Also, when animating is may be useful to first use pen and paper to write down how the animations should behave, this may help when writing the code to implement them.
I'm not sure, if i understand correctly, but what you want is this ?
var $wrapper = $('.wrapper');
function startAnimation () {
var animationCount = 4
var iterationCount = 0
var intervalValues = {
animation: 300,
loops: 900
}
function toggleAlt () {
$wrapper.toggleClass("alt");
iterationCount++
if (iterationCount > 0 && iterationCount % animationCount === 0) {
setTimeout(toggleAlt, intervalValues.loops)
} else {
setTimeout(toggleAlt, intervalValues.animation)
}
}
toggleAlt();
}
startAnimation()
i've tried to keep simple, Fiddle: https://jsfiddle.net/50gemkrk/
Toggle class few times with interval of few ms.
Wait for few ms.
Repeat first step: Toggle class few times with interval of few ms
IMHO,
I might be wrong, but setIntervals is not recommended in most of cases, it's easy to lose control
Also, i agree with Sven's answer, CSS3 Animation is cool, i recomend it !

Jquery Traversing to the Array

take a time To look at this website http://www.thejewelrysource.net/ and stay for like 7 seconds in the bottom left corner there is a small pop up that will appear and disappear again I want to do something like that using Jquery.
I know I could use Slideup and SlideDown Method but the problem I am facing is that How could traverse to the Given data in an Array so that I will Pop up the Data One at a Time. I am using only Static Data. Thank you for your Help in Advance! may someone help me! Thank You So Much
I couldn't understand much from your description. By any chance is this what are you looking are?
I have used setTimeout and setInterval to simulate this and a closure variable to keep track of the next item to display.
$(document).ready(function() {
var $popup = $(".popup"),
aMessages = ["Hello", "This is alert", "Is this what are you look for?"],
counter = 0;
$(".popup").hide();
var interval = setInterval(showMessage, 3000);
function showMessage() {
var iMessageId = counter % aMessages.length;
$popup.text(aMessages[iMessageId]);
$popup.show();
counter++
setTimeout(hideMessage, 1000);
}
function hideMessage() {
$(".popup").fadeOut(100);
}
setTimeout(function() {
clearInterval(interval);
}, 10000);
});
.popup {
width: 200px;
height: 100px;
background-color: yellow;
border-radius: 50px;
padding: 20px;
position: fixed;
left: 10px;
bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="popup"></div>

Slide effect between two divs with jQuery?

I found this JSFiddle with a similar effect I'm looking for
But, I need to add the effect of fade In when the hidden div appears and also when this one gets back to hide.
I tried to add an effect from Animate CSS but it didn't work
$('#yourElement').addClass('animated bounceOutLeft');
Is this what you are looking for? Instead of moving the inner div left and right, we keep the home and member-home divs at the same spot with one as hidden using css.
#member-home {
display:none;
position:absolute;
left:0px;
width: 400px;
height: 600px;
background-color: green;
}
Then on button click we just use fadeToggle() with animation duration as 2000 to fade in the first showing div and fade out the hidden div and vice versa. No need of a seperate function with if-else conditions.
$("button").bind("click", function() {
$("#home").fadeToggle(2000);
$("#member-home").fadeToggle(2000);
});
Here is example code.
http://codepen.io/Nasir_T/pen/vXPjqy
Hope this helps.
update function as below.
function toggleDivs() {
var $inner = $("#inner");
// See which <divs> should be animated in/out.
if ($inner.position().left == 0) {
$inner.animate({
opacity: 1,left: "-400px"
},2000);
}
else {
$inner.animate({
opacity: 1,left: "0px"
},2000);
}
}
Try this: http://jsfiddle.net/1cgs9evo/1/
function toggleDivs() {
var $inner = $("#inner");
if ($inner.position().left == 0) {
$inner.fadeOut('slow');
$inner.animate({
left: "-400px"
});
$inner.fadeIn('slow');
} else {
$inner.fadeOut('slow');
$inner.animate({
left: "0px"
});
$inner.fadeIn('slow');
}
}

Event 'transitionend' is called too early, it delays rendering

What I'm doing and what's wrong
When I click on a button, a slider shows up. (here is an example of what it looks like, do not pay attention to this code)
The slider shows via an animation. When the animation is finished I should include an HTML page I've loaded from the server. I need to apply the HTML in the slider after the animation otherwise the animation stops (the DOM is recalculated).
My algorithm
Start the request to get the HTML to display inside the slider
Start the animation
Wait the data to be ready and the transition to be finished
Why? If I apply the HTML during the animation, it stops the animation while the new HTML is added to the DOM. So I wait for both to end before step 4.
Apply the HTML inside the slider
Here is the shortened code:
// Start loading data & animate transition
var count = 0;
var data = null;
++count;
$.get(url, function (res) {
data = res;
cbSlider();
});
// Animation starts here
++count;
$(document).on('transitionend', '#' + sliderId, function () {
$(document).off('transitionend', '#' + sliderId);
cbSlider()
});
function cbSlider() {
--count;
// This condition is only correct when both GET request and animation are finished
if (count == 0) {
// Attempt to enforce the frame to finish (doesn't work)
window.requestAnimationFrame(() => { return });
$('#' + sliderId + ' .slider-content').html(data);
}
}
The detailed issue
transitionend is called too early. It makes the last animated frame a lot too long (477.2ms) and the last frame is not rendered at transitionend event.
From the Google documentation, I can tell you that the Paint and Composite step of the Pixel Pipeline is called after the Event(transitionend):
Maybe I'm overthinking this.
How should I handle this kind of animations?
How can I wait the animation to be fully finished and rendered?
I'm not sure why transitionend is fired before the last frame has rendered, but in this (very crude) test it seems that a setTimeout does help...
The first example shows how the html calculation and injection happens too early. The second example wraps the long running method in a setTimeout and doesn't seem to trigger any interuption in the animation.
Example 1: reproduction of your problem
var ended = 0;
var cb = function() {
ended += 1;
if (ended == 2) {
$(".animated").html(createLongHTMLString());
}
}
$(".load").click(function() {
$(".animated").addClass("loading");
$(".animated").on("transitionend", cb);
setTimeout(cb, 100);
});
function createLongHTMLString() {
var str = "";
for (var i = 0; i < 100000; i += 1) {
str += "<em>Test </em>";
}
return str;
};
.animated,
.target {
width: 100px;
height: 100px;
position: absolute;
text-align: center;
line-height: 100px;
overflow: hidden;
}
.target,
.animated.loading {
transform: translateX(300%);
}
.animated {
background: green;
z-index: 1;
transition: transform .2s linear;
}
.target {
background: red;
z-index: 0;
}
.wrapper {
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="animated">Loading</div>
<div class="target"></div>
</div>
<button class="load">load</button>
Example 2: in which a setTimeout seems to fix it
With a setTimeout around the html injection code.
var ended = 0;
var cb = function() {
ended += 1;
if (ended == 2) {
setTimeout(function() {
$(".animated").html(createLongHTMLString());
});
}
}
$(".load").click(function() {
$(".animated").addClass("loading");
$(".animated").on("transitionend", cb);
setTimeout(cb, 100);
});
function createLongHTMLString() {
var str = "";
for (var i = 0; i < 100000; i += 1) {
str += "<em>Test </em>";
}
return str;
};
.animated,
.target {
width: 100px;
height: 100px;
position: absolute;
text-align: center;
line-height: 100px;
overflow: hidden;
}
.target,
.animated.loading {
transform: translateX(300%);
}
.animated {
background: green;
z-index: 1;
transition: transform .2s linear;
}
.target {
background: red;
z-index: 0;
}
.wrapper {
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="animated">Loading</div>
<div class="target"></div>
</div>
<button class="load">load</button>
Well, if transitions are not working for you the way you want to, you can go back a few years and use jQuery animations instead?
(function(slider){
$.get(url, function (res) {
slider.animate({
// put whatever animations you need here
left: "5%",
}, 5000, function() {
// Animation complete.
slider.find('.slider-content').html(res);
});
});
}($('#' + sliderId)));
You can also start both actions at the same time, and then add the html to the document only after the animation has finished and the request is complete, but that would require a flag.
(function(slider){
// whether the animation is finished
var finished = false;
// whether the html has been added already
var added = false;
// your html data
var html = null;
function add() {
if (finished && html && !added) {
// make sure function will only add html once
added = true;
slider.find('.slider-content').html(html);
}
}
$.get(url, function (res) {
html = res;
add();
});
slider.animate({
// put whatever animations you need here
left: "5%",
}, 5000, function() {
// Animation complete.
finished = true;
add();
});
}($('#' + sliderId)));

Forcing a layer repaint

I have a kiosk application running on Ubuntu server 14.04.3 and chrome. Currently I have some code which hides the mouse if there was no movement for 2 seconds and once the user attempts to move the mouse again it shows up again. The trick is by using a cursor:none and adding an overlay:
js:
var body = $('body');
function hideMouse() {
body.addClass("hideMouse");
body.on('mousemove', function(){
if(window.hiding) return true;
window.hiding = true;
body.removeClass("hideMouse");
$('div.mouseHider').remove();
clearTimeout(window.hideMouse);
window.hideMouse = setTimeout(function(){
body.addClass("hideMouse");
$('<div class="mouseHider"></div>').css({
position: 'fixed',
top: 0,
left: 0,
height: '100%',
width: '100%',
zIndex: 99999
}).appendTo(body);
redraw(document.body);
setTimeout(function(){
window.hiding = false;
}, 100);
}, 4000);
});
}
function redraw(e) {
e.style.display = 'none';
e.offsetHeight;
e.style.display = 'block';
}
css:
body.hideMouse *, body.hideMouse{
cursor: none;
}
body.hideMouse *{
pointer-events: none !important;
}
This code works perfectly fine but there is only 1 caveat. When the page first loading it attempts to hide the mouse with the same trick but the mouse is still sticking there since it just didn't repainted the layer I guess. If I want it to work, I have to move the mouse a little bit and from then on it will work as expected and hide the mouse. The thing is that the kiosk application is restarting every day which means I boot the X display again and the mouse is being reset to the middle of the screen and it just sticks there until I move it a little bit. I hope you understand what I mean.
Do you guys have any idea how I can fix this?
You don't need all that code to do what you want. You could do:
Create a setTimeout to hide the cursor after 2s as soon as the page is loaded
When someone moves the mouse, you:
2.1. Show the cursor again
2.2. Clear the current setTimeout
2.3. And create the setTimeout to hide the cursor after 2s again.
The code below should work for you:
document.addEventListener('DOMContentLoaded', function() {
var cursorNone = document.getElementById('cursor-none');
var t = setTimeout(hideMouse, 2000);
document.addEventListener('mousemove', function(e) {
showMouse();
clearTimeout(t);
t = setTimeout(hideMouse, 2000);
});
function hideMouse() {
cursorNone.classList.remove('hidden');
}
function showMouse() {
cursorNone.classList.add('hidden');
}
});
#cursor-none {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
cursor: none;
background-color: transparent;
}
.hidden {
display: none;
}
<body>
<div id="cursor-none" class="hidden"></div>
</body>

Categories