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.
Related
I have this burger menu which I can't invoke the button onclick event function when I click it.
HTML code:
<button class="nav-aside-close"><i class="fa fa-times"></i></button>
JQuery code:
$('.nav-aside-close').on('click', function () {
console.log('test');
$('#nav-aside').removeClass('active');
$('#nav').removeClass('shadow-active');
});
If I click any area outside the burger menu, it works. Below is the code which works:
$(document).click(function(event) {
if (!$(event.target).closest($('#nav-aside')).length) {
if ($('#nav-aside').hasClass('active')) {
$('#nav-aside').removeClass('active');
$('#nav').removeClass('shadow-active');
} else {
if ($(event.target).closest('.aside-btn').length) {
$('#nav-aside').addClass('active');
$('#nav').addClass('shadow-active');
}
}
}
});
Actual code I have uploaded it at http://js.findingsteve.net
If you're using Chrome, open up DevTools (F12) and do this on the Console tab and hit Enter:
getEventListeners(document.querySelector('button.nav-aside-close'))
If you see any click events registered, it should work.
Anyway, I noticed you are putting the main.js file on the <head> and not using jQuery.ready, so your click handler is essentially never attached since the DOM element is not ready by the time the script executes.
Solution:
Add the jQuery alias $ on the very first line of your JS file, that is a shorthand for jQuery.ready BTW.
$(function($) {
"use strict"
// Fixed Nav
var lastScrollTop = 0;
Don't forget to also remove the jQuery function assignment from the end of the line, since it's no longer an IIFE.
setStickyPos();
})(jQuery);
Alternative, you can keep everything as is and move your main.js file to the <body> element, right before the closing </body> tag. That is pretty much the same as having the scripts executed when all the elements above it have finished loading.
It's probably because .nav-aside-close is hidden in the initial render.
Try this instead:
$("#nav").on("click", ".nav-aside-close", function() {
$("#nav-aside").removeClass("active");
$("#nav").removeClass("shadow-active");
});
Based in #Ana Liza Pandac comment
It should be:
$("#nav").on("click", "#nav-aside .nav-aside-close", function() {
$("#nav-aside").removeClass("active");
$("#nav").removeClass("shadow-active");
});
Your tree is: nav->nav-aside and obj with class nav-aside-close
The difference is on:
$("#nav").on("click", "#nav-aside .nav-aside-close", function()
I have jQuery-2.1.4.min.js called before the tag, but when I write something like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
alert('hi, world.');
});
</script>
On my PC it is fired of course, but on ten different Android devices it just does not. This is purely HTML/CSS/jQuery rendered site (no phonegap, or anything).
My goal was to have a button do ajax request after it's being tapped, but I can't even test that, because the .ready() function is not firing at all on mobile chrome.
The jQuery is being served from the official CDN, any help would be very much appreciated.
Tried both:
$(function() {
alert('hi, world.');
});
And
jQuery(document).ready(function() {
alert('hi, world.');
});
Same thing.
As suggested I also tried:
window.onload = function()
{
if (window.jQuery)
{
alert('jQuery is loaded');
}
else
{
alert('jQuery is not loaded');
}
}
And it alerts 'jQuery is loaded'.
As per jQuery docs it says: "Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute" - which would mean that DOM is not ready for JavaScript code to execute? But when I try like:
<script type="text/javascript">
alert('hi world');
</script>
It executes on mobile Chrome.
Okay, after extensive investigation it seems that JS breaks on mobile chrome if you have document.ready() function twice, I had one in my core.js file and one in-line on the page.
It works okay on PC (all browsers), but on mobile it works up to the point of second ready() call and breaks all JS after that.
Hopefully this saves some time to others in the future.
JS breaks on mobile view becouse same js use multiple time in file. Check and remove redundancy.
At my website, I am loading jQuery asynchronously.
In order to do that, I must run jQuery functions only after it is really loaded.
I've tried two pure JS ways:
<script src="js/jquery-2.2.2.min.js" async></script>
<script>
window.addEventListener('load', function() {
//stuff
}, true);
</script>
And
window.onload = function() {
//stuff
}
But even so I still get Uncaught TypeError: $(...) is not a function at...
How do I fire jQuery functions after the lib is fully loaded?
You need to add the script only after jQuery library is loaded using script tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// your code should be here
alert(typeof jQuery)
</script>
The document ready handler is using to execute the code only after DOM elements are loaded.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
console.log('Outside document ready handler ' + $('.test').length)
$(document).ready(function() {
console.log('Inside document ready handler ' + $('.test').length)
});
</script>
<div class="test"></div>
UPDATE 1: You can use defer if script is in a file, refer following question: jquery loaded async and ready function not working
UPDATE 2: Or you can bind load event handler to the script tag using addEventListener method.
<script async id="script" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('script')
.addEventListener('load', function() {
alert(typeof jQuery)
});
</script>
FYI : I don't know why you are doing this, for optimizing the speed of content load it's always better to move the script tags at the end of body which helps to load content first.
You could do something like this:
function checkVariable(){
if ( window.jQuery){
Do your jquery stuff here
}
else{
window.setTimeout("checkVariable();",100);
}
}
checkVariable();
Apologies for the formatting...stuck on my phone right now.
I did not see this method listed, so I thought I would demonstrate using the JavaScript HTML DOM EventListener.
Example #1 Using the jQuery.ready() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
$(document).ready(function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will not work since jQuery has yet to be loaded.
Running the above example will output:
ERROR: {
"message": "ReferenceError: $ is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 13,
"colno": 3
}
Example #2 Using the addEventListener() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
window.addEventListener('DOMContentLoaded', function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will work since we are listening for the Window DOMContentLoaded event.
From Mozilla:
The original target for this event is the Document that has loaded.
You can listen for this event on the Window interface to handle it in
the capture or bubbling phases. For full details on this event please
see the page on the Document: DOMContentLoaded event.
A different event, load, should be used only to detect a fully-loaded
page. It is a common mistake to use load where DOMContentLoaded would
be more appropriate.
You can use this:
<script>
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
// window loaded, external resources are loaded too...
jQuery(function($) {
// your code here: $("a").css(...)
}
}
});
</script>
I used it when inline jQuery script did not work on safari (Mac and iOS) and this solved the problem.
Use document.ready or load the library in the header. That should work.. Be sure to load in the right folder or in the right link. If you are usying a link to load jquery then be sure to have an internet connection
I'm having what seems to be a really simple issue that I really can't find a solution for:
In my code I have a script loaded in the header:
<script type="text/javascript" src="../js/viewdoc/index.js?v=1.33"></script>
In that specific script I declare the functions:
function addResizeListener(listener){
//Attach the back button function to window resize event
if(window.attachEvent) {
window.attachEvent('onresize', listener); //Old browsers
}
else if(window.addEventListener) {
window.addEventListener('resize', listener, true); //New browsers
}
}
and:
function removeResizeListener(listener){
//Remove the listener for the back button
if(window.detachEvent) {
window.detachEvent('onresize', listener);
}
else if(window.removeEventListener) {
window.removeEventListener('resize', listener, true);
}
}
then I load this file into the element with a loaderdoc id:
if ($('#loaderdoc').is(':empty')){
$('#loaderdoc').load('../viewdoc/welcome.php');
}
I use the function addResizeListener to bind a function to the window resize event, this works perfectly, and the index.js script ends.
In the end of the loaded file welcome.php i added the line
<script src="../js/viewdoc/welcome.js"></script>
welcome.js is a script that uses the functions removeResizeListener and addResizeListener, but I get the error:
Uncaught ReferenceError: addResizeListener is not defined
Why is this? Wasn't the functions defined and loaded before the script was added to the document?
Sorry if this was answered before, I just couldn't really find it, or maybe I don't know he right way to search for it yet.
And thanks for reading!
jQuery's .load() is async. Thus welcome.js will be executed, before the functions are defined. You have to use a callback. See https://api.jquery.com/load/
I created this test case which works as expected:
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="site.js"></script>
<script>
function click_me() {
deActivateButton("Please wait ..", "#btnX");
activateButton("Click me 2", "#btnX");
}
</script>
<button type="button" id="btnX" onclick="click_me(); return false;">Click me
</button>
And then two small functions kept in site.js to deactivate/activate my buttons:
function deActivateButton(btnText, id) {
$(id).text(btnText);
$(id).prop("disabled", true);
}
function activateButton(btnText, id) {
$(id).text(btnText);
$(id).prop("disabled", false);
}
This works fine, but fails when I use the code in my application. I'm using web forms with a master page. The master page loads include file:
<%Response.WriteFile("Content/Files/master_include_head.html");%>
And then in master_include_head.html I include the actual javascript functions like this:
<script src="site.js"></script>
What can I be doing wrong here? There are no error messages, it just dies. Shouldn't I be able to reference the id of the clicked button with this design, or is the reference to the button lost because of the way I include files? Can it be a cache problem?
Are you not just setting and then clearing then immediately clearing the value in your code?
So you are activating then immediately de-activating your button?
Just a little note. Why not use jQuery to attach your click events as follows:
$("#btnX").click(function(e) {
// Do stuff
});
Side note. I'm not sure there's any need for the return false; statement in your onclick. Typically this would just contain the function name. return false; can be used in functions to prevent event bubbling, as you've set it I'm not sure it will have any effec