Execute Javascript after Div populated with Javascript has loaded - javascript

I am trying to exceute a javascript function after another div that has been popupated by javascript has loaded. The div has been populated first with javascript is '#am-events-booking'. The function i am trying to use is:
$(window).load(function ()
{
var i = setInterval(function ()
{
if ($('#am-events-booking').length)
{
clearInterval(i);
}
}, 1000);
alert('Page is loaded');
});

I always use $(document).ready() to run code after the page has loaded. Not sure what the difference is, but at least then it works.
Furthermore you need to use .text() to get the text inside an element.
Working code snippet:
$(document).ready(function() {
var i = setInterval(function() {
if ($('#am-events-booking').text().length) {
clearInterval(i);
console.log('Text detected!');
} else {
console.log('Waiting...');
}
}, 1000);
console.log('Page is loaded');
});
setTimeout(loadText, 2200);
function loadText() {
$('#am-events-booking').html("<h2>Hello</h2>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="am-events-booking"></div>

$(document).ready(findDiv);
function findDiv() {
if($('#am-events-booking').is(':visible')){ // if the div is visible
alert('Page is loaded');
} else {
console.log("loading...");
setTimeout(findDiv, 50); // wait 50ms,
}
}
$('body').html('<div id="am-events-booking"></div>');
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use is :visible form JQuery to check if div is added or not

Related

Convert $(document).ready() function into window.onload function?

I have a jQuery function :
$(document).ready(function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available").html(data);
});
}, 3000);
}
I have to convert it into window.onload function.
How to do it?
If you want it vanilla js, use onload callback of the window object:
window.onload = function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available" ).html(data);
});
}, 3000);
}
But you could even use load event with jQuery, what is basically the same:
$(window).on('load', function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available").html(data);
});
}, 3000);
});
But keep in mind, that a jQuery ready state is not the same as window.onload. These are two different things. So this might have unexpected impacts to your project/page.
You can handle the readystatechange event,
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
// Your code
}
}
window.onload waits for everything, including images, which probably is overkill.

how to show two div one by one repeatedly

i am working on developing on an Html page where i have two div. In each div i have one image. I want that each image should be visible for 2 second and after that the second div should get visible. This function should get repeatedly. For this i used following code.
<script type="text/javascript">
$( document ).ready(function() {
$(".logo-outer").show();
setTimeout(function () {
$(".logo-outer").hide();
$(".logo-outernew").hide();
}, 2000);
});
</script>
But the above code is not working and image in not visible or invisible.
you can make use of SetInterval function instead of timeout function
below is example code , it might now working please check proper function . main point is make use of interval function
var myInterval = setInterval(function () {
if($(".logo-outer").is(':visible'))
{
$(".logo-outer").hide();
$(".logo-outernew").show();
}
else
{
$(".logo-outer").show();
$(".logo-outernew").hide();
}
},2000);
if you want to stop
clearInterval(myInterval);
setInterval(function () {
if ($(".logo-outer").css("display") == "none"){
$(".logo-outer").show();
}
else{
$(".logo-outer").hide();
}
}, 2000);
Every 2seconds it runs the functions and if logo outer is not visible it will show it, else if it's visible it will hide it.
I believe that you have also made an error in hiding the second image insted of displaying it (inside setTimeout):
$(".logo-outer").hide();
$(".logo-outernew").hide();
I believe the second one should be $(".logo-outernew").show();?
You can use the modulo (e.g. % sign) operator with a global variable to determine when hide or show your divs.
var count = 0;
$( document ).ready(function() {
$(".logo-outer").show();
setTimeout(function () {
if(count % 2 == 0) {
$(".logo-outer").hide();
$(".logo-outernew").show();
} else {
$(".logo-outer").show();
$(".logo-outernew").hide();
}
count++;
}, 2000);
});
By default hide your 2nd div and inside setTimeout hide your 1st dive and show your second div.
$(".logo-outer").show();
$(".logo-outernew").hide();
setTimeout(function () {
$(".logo-outer").hide();
$(".logo-outernew").show();
}, 2000);
.logo-outer {
background:red;
width: 50vw;
height: 50vw;
}
.logo-outernew {
background:green;
width: 50vw;
height: 50vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo-outer">
<h1>1 div</h1>
</div>
<div class="logo-outernew">
<h1>2 div</h1>
</div>
function swapImage() {
$('.img02').fadeOut();
$('.img01').fadeIn();
setTimeout(function () {
$('.img02').fadeIn();
$('.img01').fadeOut();
}, 2000);
setTimeout(function () {
swapImage();
},4000)
}
$(document).ready(function () {
swapImage();
});
.img01,
.img02{
width: 200px;
height: 200px;
position: absolute;
}
.img01{
background: green;
}
.img02{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img01"></div>
<div class="img02" style="display: none;"></div>
Remove the console and un-comment the lines with hide and show function
var time_to_display = 2000;
var img1 = setInterval(function () {
console.log("Img1");
// $(".logo-outer").hide();
// $(".logo-outernew").show();
}, time_to_display * 2);
setTimeout(function(){
var img2 = setInterval(function () {
console.log("Img2");
// $(".logo-outernew").hide();
// $(".logo-outer").show();
}, time_to_display * 2);
},2000);
You can simply change display for one div to none and use the following code it will hide and show
<script>
$(document).ready(function(){
setInterval(function(){
$("div.logo-outer, div.logo-outernew").toggle(1000);
}, 3000)
});
</script>

Consolidate javascript timeout functions

Sorry for the basic level of the question, but js definitely isn't my area of expertise. However, it's one of those questions that's difficult to Google an answer on.
I basically want to do a couple of things when the window is resized. I have a little bit of extra code that also stops the resize event firing twice.
The issue is that I'm duplicating bits of code, that as a coder, I know is wrong. The problem is I don't know how to go about making it right. Here's my current duplicated code:
Event binding
$(window).on("resize", resizeText);
$(window).on("resize", resizeIndicator);
Functions
function resizeIndicator() {
clearTimeout(id);
id = setTimeout(updateIndicator, 200);
}
function resizeText() {
clearTimeout(id);
id = setTimeout(updateText, 200);
}
Thse are not duplicated but included for completeness:
function updateIndicator() {
$tab = $(".tabs li.focus");
if ($tab.length) {
toggleIndicator($tab, true);
}
}
function updateText() {
$tabs = $(".tabs li:not(.indicator) a");
$tabs.each(function () {
$(this).toggleClass("two-line", this.scrollWidth > $(this).outerWidth());
});
}
So you want to avoid code duplication? No problem use higher order of function to create new function.
function createResizeCallback(resizeFunc) {
var id;
return function () {
clearTimeout(id);
id = setTimeout(resizeFunc, 200);
}
}
$(window).on("resize", createResizeCallback(updateText));
$(window).on("resize", createResizeCallback(updateIndicator));
function updateIndicator() {
console.log('updateIndicator');
}
function updateText() {
console.log('updateText');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Declare your timeout id globally and use single handler.
Working demo: http://jsbin.com/nugutujoli/1/edit?js,console,output
$(window).on("resize", resizeEvent);
var timeout;
function resizeEvent() {
clearTimeout(timeout);
timeout = setTimeout(function(){
updateIndicator();
updateText();
}, 200);
}
function updateIndicator() {
console.log("update indicator fired.");
}
function updateText() {
console.log("update text fired.");
}

Jquerymobile Loading spinner Dialog before page is Loaded

In my app I have 3 pages from the first page I am sending data to server, here I want to show a Loading dialog until the send operation (posting to server) is finished and then go to page two. Doing a below but it's not working
<script type="text/javascript">
$(document).on('pageshow', '#Page2' ,function () {
setTimeout(function () {
$.mobile.changePage('#dialog');
}, 100); // delay above zero
});
</script>
Try2
<script>
$(document).on("pagecreate","#page", function () {
$("#custom-li").on("click", function () {
var orgname = $('input:text[id=name]').val();
loadingStart();
setTimeout(function () {
loadingEnd();
$.mobile.changePage('#page2');
}, 3000);
return false;
});
});
function loadingStart() {
$.mobile.loading('show', {
text: "loading",
textVisible: true
});
}
function loadingEnd() {
$.mobile.loading("hide");
}
</script>
the function is firing but the spinner is missing from the dialog when I run in browser and mobile.
Any help is appreciated.
So is only spinner missing? In this case, maybe you don't have "images/ajax-loader.gif" at html files directory.

Using setTimeout to delay timing of jQuery actions

I am attempting to delay the swapping of text in a div. It should operate like a slider/carousel for text.
I must have the code wrong, as the final text replacement never happens.
Also, how would I animate introducing the replacement text (window blinds, for eg.)?
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function() {
$("#showDiv").click(function() {
$('#theDiv').show(1000, function() {
setTimeout(function() {
$('#theDiv').html('Here is some replacement text', function() {
setTimeout(function() {
$('#theDiv').html('More replacement text goes here');
}, 2500);
});
}, 2500);
});
}); //click function ends
}); //END $(document).ready()
</script>
</head>
<body>
Below me is a DIV called "theDiv".<br><br>
<div id="theDiv" style="background-color:yellow;display:none;width:30%;margin:0 auto;">
This text is inside the Div called "theDiv".
</div><br>
<br>
<input type="button" id="showDiv" value="Show DIV">
</body>
</html>
.html() only takes a string OR a function as an argument, not both. Try this:
$("#showDiv").click(function () {
$('#theDiv').show(1000, function () {
setTimeout(function () {
$('#theDiv').html(function () {
setTimeout(function () {
$('#theDiv').html('Here is some replacement text');
}, 0);
setTimeout(function () {
$('#theDiv').html('More replacement text goes here');
}, 2500);
});
}, 2500);
});
}); //click function ends
jsFiddle example
Try this:
function explode(){
alert("Boom!");
}
setTimeout(explode, 2000);
You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:
$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.
This is how I solved the problem
The menu closes a few seconds after mouse out (that if hover didn't fire),
//Set timer switch
$setM_swith=0;
$(function(){
$(".navbar-nav li a").click(function(event) {
if (!$(this).parent().hasClass('dropdown'))
$(".navbar-collapse").collapse('hide');
});
$(".navbar-collapse").mouseleave(function(){
$setM_swith=1;
setTimeout(function(){
if($setM_swith==1) {
$(".navbar-collapse").collapse('hide');
$setM_swith=0;}
}, 3000);
});
$(".navbar-collapse").mouseover(function() {
$setM_swith=0;
});
});

Categories