Why does this code sometimes not run when refreshing the page? - javascript

I have a page loading element which displays during the pageload and is then removed. Most of the time, this works, but sometimes it doesn't so the user is left staring at the loader forever.
It usually works, but sometimes it doesn't when refreshing the page. In Chrome, if I open developer tools, then it does always work fine.
document.addEventListener('DOMContentLoaded', function (event) {
console.log("removing loader");
$('.preloader').fadeOut(500, function () { $('.preloader').remove(); });
});
window.addEventListener('load', function (event) {
console.log("removing loader");
$('.preloader').fadeOut(500, function () { $('.preloader').remove(); });
});
This code is in a js file, and I think what happens is that the file is cached, so it doesn't run again during the refresh. Does the sound correct? Should I just put this in a script tag to ensure it always runs?
I put the code in both events as I was having issues with it sometimes not running. However, maybe this is not actually necessary.

If there are any errors during the loading of elements, some listeners can fail to trigger. Have to tried the simple,
$(document).ready(function(){
console.log("removing loader");
$('.preloader').fadeOut(500, function () { $('.preloader').remove(); });
});

Related

jQuery .trigger() isn't being caught

Does jQuery .trigger() or .triggerHandler() work across two separate JavaScript files? I have a timeline that when interacted with, triggers a function
scrubbingToTime(position). In a separate JavaScript file, I want to detect when scrubbingToTime(position) is being called, so I was looking into jQuery .trigger(). The code is hard to reproduce, but the idea was that it was like:
timeline.js
function scrubbingToTime(position) {
$(document).trigger("scrub", [position]);
}
catch.js
$(document).on("scrub", function(e, pos) {
console.log("Time Changed!");
});
This does not work, however if the trigger and on are in the same file, it works fine. For example,
timeline.js
function scrubbingToTime(position) {
$(document).trigger("scrub", [position]);
$(document).on("scrub", function(e, pos) {
console.log("Time Changed!");
});
}
This actually console.logs the Time Changed! message. Is there any reason why the first (what I want) won't work?
You need to make sure the order of the JS loading is correct.
If you are loading your catch.js file first, then timeline.js won't know about scrub because it hasn't been loaded yet.

Selector only working after inspecting/selecting element

I have this code here:
$(document).ready(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('Hello'); });
});
The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []
But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.
I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.
$(document).ready(function() {
//debugger;
setTimeout(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('allo'); });
}, 10000);
});
Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?
I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.
The reason it works when you inspect an element, is Chrome has selected the execution context for you already.
Discussion about iFrame context in Dev Tools
Using the "on", it works even if the element exists after the page loads.
$(document).ready(function(){
//$("div[id^='stage_']").click( function (e) { alert('Hello'); });
$("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
$('body').html('<div id="stage_1">teste1</div>' +
'<div id="stage_2">teste2</div>' +
'<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc: http://api.jquery.com/on/

OnClick works only works after reload, using jquerymobile

I know it's an often asked question, but no answer (till now) fits for me.
I wrote a mobile app with Cordova. I'm also testing apps in browser (Firefox). I'm using jQuery and jq mobile.
The problem is: my OnClick events on work only after refresh, which isn't possible on mobile and even on pc not really an solution.
Update: I read about, that the ehader isn't loaded again in jQuery mobile. So I treid it as described in thsi solution: page loaded differently with jQuery-mobile transition
didn't work.
And with alert(); you see, that the script runs once but before the site is totally build.
My html:
<div data-role="main" class="ui-content" id="container" >
<div id="container0">
<a data-role="button" id="anchor0" >Neuen Termin Hinzufügen</a>
</div>
</div>
originally the <a> had an onclick (<a onClick>="doStuff()")
Here a are my different attempts:
$(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
});
$(document).ready($(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
})
);
$("#anchor0").live("click", dateElementClicked($("#anchor0")));
$("a").click( dateElementClicked(this));
$("a").bind("click", function (event, ui){
dateElementClicked(this);
});
They all work only after an refresh. or the first one runs the function instant and interupts everything because "this" is undefined.
Edit:
I even tried it with button and inpute type button and made extra js file. but my javascript only runs after an refresh... Putted an console log and alert in the script. So the whole script is stuck somehow
The dateelement clicked function (I cleared this too for testing and just put an alert() in it)
Here is the git link to the project: https://github.com/LosKartoflos/Apoll.git
function dateElementClicked(clickedAnchor) {
//anchor is clicked the first time(the id number equals numberOfAppointments)
if (clickedAnchor.id.slice(-1) == numberOfAppointments) {
dateElementClickedFirstTime(clickedAnchor);
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == true)
{
hideContent(getDateElementNumber(clickedAnchor));
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == false)
{
showContent(getDateElementNumber(clickedAnchor));
}
else
{
alert("Element not listed");
}
}
BTW: my script isin my html file.
Maybe try using the deviceready event instead of document ready.
https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
Try this
$(document).on('click', '#anchor0', function(event) {
});
or this
$(document).on('click', 'a', function(event) {
});
okay the Problem is, that Cordova is messing around with normal build/loading oder. to trigger functions, after the side is loaded.
The Cordova Documentary recommends this two solutions:
Put this in your header and bind your events in the onload or dofirst. An do everything you want to be have done, after page is ready, in the do first:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/script.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//add all Events (click Events)
function onLoad() {
document.addEventListener("deviceready", doFirst(), false);
document.getElementById("anchor").addEventListener("click", clickedFunction, false);
}
// device APIs are available
function onDeviceReady() {
}
//things to put up first
function doFirst() {
}
</script>
or put it in the onDeviceReady function, in the auto created index.js .
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
document.getElementById("anchor0").addEventListener("click", clicked, false);
app.receivedEvent('deviceready');
},
Here the documentary: https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
And i kicked out jquery and jquery mobile. Jquery was messing around with document ready and jquery mobile prevents the head from beeing loaded again.

How to run a Javascript function everytime f5 is used to refresh the page

The following code works for the first time that the page is loaded but when the page is refreshed using F5, it does not work on Firefox. In Chrome it works fine.
$(document).ready(function() {
$("iframe").each(function() {
// Using closures to capture each one
var iframe = $(this);
iframe.on("load", function() { // Make sure it is fully loaded
iframe.contents().click(function(event) {
iframe.trigger("click");
});
});
iframe.click(function() {
alert("Clicked...");
});
});
});
This code works fine for me
$(document).ready(function () {
document.getElementById('main_iframe').contentWindow.location.reload(true);
$('iframe').load(function () {
$(this).contents().find("body").on('click', function (event) {
alert("clicked....")
});
});
});
put all your code in jQuery(function(){
//here
}) and all will be ok. That runs whens the page loads, each f5 action, remove the other code for testing reload.

document.ready() function not executed, works in dev console

I'm trying to simulate a click in a tabbed div when the page loads.
To do this I use:
$(document).ready(function() {
$("#tab_inbox").click();
});
However, this doesn't seem to work, but when I enter this in the dev console on Google chrome, it does work..
$("#tab_inbox").click();
To show the tabs, I use this code:
$("#tab_inbox").click(function() {
$("#othertab").hide();
$("#tab_inbox").show();
});
Anybody knows what's wrong?
Try this:
$(document).ready(function() {
setTimeout(function () {
$("#tab_inbox").trigger('click'); //do work here
}, 2500);
});
I read in your comment that you're using show/hide techniques and I assume you need the click for an initial display option? If so, hide (or show) your element(s) specifically in the code rather than saying click to hide/show. So
$(document).ready(function() {
$("#tab_inbox").hide();
}
Or try core JavaScript and use
window.onload = function() {
// code here
}
window.onload waits until everything is loaded on your page, while jQuery's .ready() may fire before images and other media are loaded.
you can try making your own function with pure JS:
document.getElementById('triggerElement').addEventListener('click', funtction(e) {
document.getElementById('hideElement').style.display = 'none';
document.getElementById('showElement').style.display = 'block';
}, false);

Categories

Resources