Document ready function - Not loading the code first - javascript

I have a function that works on the body onload="" but I need it to load before other elements of the page and I'm trying to add the document ready function in the header but it just doesn't seem to work.
f1menu() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
}
$(document).ready(function() {
f1menu();
});
So the onload function that works is just this one below:
onload="$('.menuH').hover(function() {$('.menuC').stop().animate({width: '90px'}, 333)}, function() {$('.menuC').stop().animate({width: '-0'}, 333)});"

Note that the following answer was provided before the OP changed the question.
You should write:
function f1menu(){}
not,
f1menu(){}
In addition, you can streamline your document.ready code by simply passing the function that you want called when the document is ready, directly to jQuery:
$(function() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'}, 333);
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333);
}
);
});
UPDATE:
After OP revised the question, the solution (not a recommended approach by the way) would be to just insert the script into the body of the page, but AFTER any elements that the function references, such as:
<body>
<!-- elements that the code references must come before the code -->
<script>
// .menuH and .menuC elements must have already been loaded into DOM
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
</script>
<!-- Rest of HTML -->
</body>

It doesnt know f1menu is a function since you didnt declare it as one. Try this:
function f1menu(){
//logic
}

Related

Call user defined jQuery function with JS

I use a jQuery window libray https://github.com/humaan/Modaal
which triggers events this way $("class of element").modaal({arg1, arg2,...});
--- I updated my question here to make it more general and used an iframe / Html instead of an external svg ---
To trigger an element e.g. in an external Html which is loaded within an iframe, I applied the following code to the iframe:
<iframe src="External.html" id="mainContent" onload="access()"></iframe>
which calls this function:
function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}
Actually it will only work on every second click. Any idea what I did not consider properly?
Best
You do not need to wait windows loading but iframe only:
$(function() {
$("#mainContent").bind("load",function(){
var myIframeElement = $(this).contents().find(".modaal");
myIframeElement.modaal({
content_source: '#iframe-content',
type: 'inline',
});
});
});
The reason why it did not work was that the iframe was not completely loaded, while jQuery tried to attach the function. As $(document).ready(function(){} did not work, the workaround was to initialize it with
$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});
This worked properly to attach the functionallity to an element within the iframe.
Actually modaal will vanish the envent handler after the overlay was opened and closed again.
So maybe someone wants to trigger an iframe element for modaal, too, here is a setup which would solve this issue.
(It can be optimised by #SvenLiivaks answer):
$(window).on("load", function() {
reload();
});
function reload() {
var length = $("#iframeID").contents().find("#IDofDIVelement").length;
// The following check will return 1, as the iframe exists.
if (length == 0) {
setTimeout(function() { reload() }, 500);
} else {
$("#iframeID").contents().find("#IDofDIVelement").modaal({
content_source: '#modalwrapper',
overlay_close: true,
after_close: function reattach() {
reload();
}
});
}
}

Defer inline jQuery Ready/Bind functions

I have some legacy jQuery executing in the page that can't be moved i.e.
jQuery(document).bind('click', function(){
console.log('click');
});
Now that loading of jQuery is at the bottom of the page 'AFTER' the above inline code, the page errors 'jQuery is undefined'
I would like to use a pattern similar to this:
var deferInlineScripts = [];
window.$ = function(inlineFunction) {
deferInlineScripts.push(inlineFunction);
};
Seen working here: https://jsfiddle.net/xpvt214o/165864/
that takes the inline scripts and executes them (Once jQuery is loaded') using
for (i = 0; i < deferInlineScripts.length; i++) {
deferInlineScripts[i]();
}
But unlike the Fiddle my legacy code doesn't have the $(function(){}); and can't be moved, changed or have anything wrapped around it i.e
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
Here is the Fiddle https://jsfiddle.net/xpvt214o/165972/ that I would like to fix so the the Bind & Ready functions execute after jQuery is loaded.
Initially define window.jQuery as a function that returns a Proxy. This proxy will allow subsequent arbitrary psuedo-propery lookups (such as .bind in jQuery(document).bind) to be performed. The properties accessed and the arguments the resulting function is eventually called with can be stored in an array and then executed once jQuery is properly loaded.
<script>
const deferCallHandler = {
get: function(jqFirstArg, jqProp) {
return function(...secondArgs) {
deferredInlineScripts.push({
jqFirstArg,
jqProp,
secondArgs,
});
}
}
};
const deferredInlineScripts = [];
window.jQuery = function(jqFirstArg) {
return new Proxy(jqFirstArg, deferCallHandler);
}
document.addEventListener('DOMContentLoaded', function(){
// window.jQuery has now been properly assigned to the true jQuery object
deferredInlineScripts.forEach(({ jqFirstArg, jqProp, secondArgs }) => {
jQuery(jqFirstArg)[jqProp](...secondArgs);
});
});
/* Can't change this code */
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
</script>
<div>some element</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Load javascript after 5 seconds after page has loaded?

I have tried the following:
<body id="myBody" onload = "setTimeout('a()', 5000)" / >
Is this the correct method? The reason why I want to do this is because I have my entire website animating in (such as fade ins) on page load. Having my javascript only makes the animation unsmooth.
Any feedback appreciated.
This code will work. Just set your time in milliseconds and write your JS code on loadAfterTime function:
<script>
window.onload = function(){
setTimeout(loadAfterTime, 5000)
};
function loadAfterTime() {
// code you need to execute goes here.
}
</script>
window.addEventListener("load", function () {
animation();
setTimeout(otherOperation, 5000);
}, false);
function animation() {}
function otherOperation() {}
maybe you can use code like this
<body id="myBody" onload = "setTimeout(a, 5000)">
Try this
if you are using jQuery your animation has a callback that you can use to delay the firing of all other javascript events like so:
$( window ).on( 'load', function () {
$( '.someElements' ).animate({
// properties to animate
}, 300, function () {
initScripts();
});
});
function initScripts () {
// call all other functions here
}
The Browser is always load all of your script if any when you open the web page. So It depend on when you call your javascript functions.
Try this:
document.ready(function(){
// your code
});
or
$(function(){
// your code
});
both of them make sure that all of element on your page have been loaded.

Perform function if body id is a specific value

I'd like to perform a function on only one page of my site where the body has an ID of #modulePage16460412. I have the script below that is not working.
<script type="text/javascript">
if($('#modulePage16460412').length > 0 ) {
$(function()
{
$(window).bind('load',
function(e)
{
window.setTimeout(function()
{
$.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"});
}, /*timeout->*/ 2000);
});
});
}
</script>
Would it also be possible to only execute the function the first time they visit the page and not execute again if they come back to that page?
Any help would be appreciated.
You can just put the function on the body load selecting it with the ID specified... if no element exists with this ID then the function will never fire.
$('#modulePage16460412').load(function() { // this will not be called unless an element with that ID has loaded into the DOM
// ... your code here.
});
and to touch on the 'single execution' part (this really should be a new question... but ohh well) you can use localStorage to persist the setting.
http://jsfiddle.net/rlemon/ET9Zg/
in your case something like
if( !getData('someKey') ) {
// ok so they have not been here.
setData('someKey', 1); // now set the data so this won't get hit again.
}
You need to put the condition inside $(function(){ so that the body tag is actually loaded before the JavaScript queries the (unloaded) DOM for the existence of the ID.
$(function(){
if($('#modulePage16460412').length) {
...
}
});
your defining a function, but not calling anywhere.
so put everything inside some function and call.
and also replace this if($('#modulePage16460412').length > 0 ) with if($('#modulePage16460412')), because when jquery couldnt find element with id : #modulePage16460412, it will return empty array. empty_array.length = 0, so it will always be true.
$('document').ready(function(){
if($('#modulePage16460412')) {
$(function()
{
$(window).bind('load',
function(e)
{
window.setTimeout(function()
{
$.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"});
}, /*timeout->*/ 2000);
});
});
}
});
Perhaps a simpler approach?
$( document ).ready( function() { // runs code only after DOM ready
if ( $( '#modulePage16460412' ).length > 0 ) { // runs code only if id found
window.setTimeout( function() {
$.colorbox( { opacity:0.3, href:"/storage/support/colorbox/offer.html" } );
}, 2000 );
}
} );

JavaScript Help Checking Passwords Match

I have this code that works on this site: http://jsfiddle.net/FPNBe/2/
However, the exact code doesn't work on my site. (With the exception I had to add
<script TYPE="text/javascript"> & < /script> around the javascript.)
Is there something I'm missing?
Wrap the script inside $(document).ready()
$(document).ready(function () {
$('#password, #confirmpassword').keyup(function() { checkPass(); } );
});
This line:
$('#password, #confirmpassword').keyup(function() { checkPass(); } );
Must only be executed after the elements in question have been added to the DOM (Document Object Model) by the browser, so that jQuery can find them. To wait until the DOM is ready, meaning that all the page's elements are accessible, you can put this line inside a function, which you can pass to jQuery:
$(document).ready(function() {
$('#password, #confirmpassword').keyup(function() { checkPass(); } );
});
Or a bit shorter:
$(function() {
$('#password, #confirmpassword').keyup(function() { checkPass(); } );
});

Categories