I've updated the script here to give a better example. For $header I've got an anonymous function now returning $("#header"). Although this works I'm sure its not efficient as it calls $header every time it's used - so its the same as just using $("#header") throughout the code.
What I really want is to store $("header") in a variable. When I try to do this with $header2 (below) it fails. #header is red not blue.
When I use firebug to output lib.page.$header2.selector is correctly displays #header. As you can see the script which calls lib.page.init is at the bottom of the DOM.
Any ideas?
<script type="text/javascript">
var lib = {
page : {
$header : function() { return $("#header")},
$header2 : $("#header"),
init: function() {
lib.page.$header().css("background","red");
lib.page.$header2.css("background","blue");
console.log(lib.page.$header2.selector);
}
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<em>Example!</em>
</div>
</div>
<script type="text/javascript">
$(function() { lib.page.init(); });
</script>
</body>
Because when you define $header : $('#header') that element is not available? and when you call lib.page.init it is? I am not sure when you call lib.page.init, but I bet it's in $(document).ready() right? And you define the object literal before the dom is ready.
Ok, your div#header is not available by the time you want to assign it to $header, you have two options and I will show you the best option first. It's what I meant with 'put all scripts at the bottom'!
<head>
<!-- dont put scripts here if you can avoid it, it's bad! -->
</head>
<body>
<div id="wrapper">
<div id="header">
<em>Example!</em>
</div>
</div>
<!-- keep scripts at the end of the page just before the </body> tag -->
<script type="text/javascript">
var lib = {
page : {
// div#header is available
$header : $("#header"),
init: function() {
lib.page.$header().css("background","red");
}
}
}
// you don't need onDomReady anymore.
lib.page.init();
</script>
</body>
Another option if you want to keep scripts in the header, is to assign $header in your onDomReady call.
<script>
// create lib etc here
$(function(){ // this is an onDomReady call in jQuery
lib.page.$header = $('#header');
lib.page.init();
});
</script>
"This happens because the variables are instantiated at the time the script is interpreted.
So at the time of the parser gets to the script the $("#header") isn't in the DOM yet."
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
Is possible to do this? For example I have this code:
#section('content' onload='MyFunction')
<!--PAGE CONTENT...-->
<div>
<h1>Something...</h1>
<select name="sel"></select>
</div>
#endsection
<script type="text/javascript">
function MyFunction(){
obj = document.forms[0].sel;
for (i=0; i<23; i++) {
//A similar condition to onload() event.
}
</script>
Or is it wrong of me to do that so? I'm working in Laravel and PHP. Or maybe using a Jquery function similar to the function in javascript.
You must understand that #Section is a blade tag. Blade tags are processed inside PHP. Also, the blade syntax does not accept the parameter onload as you want.
Also, either on HTML/JS you can't use onload as you want.
You have two alternatives:
1 - Put a script tag after the section:
#section('content')
<!--PAGE CONTENT...-->
<div>
<h1>Something...</h1>
<select name="sel"></select>
</div>
<script>
// Note that this function must have been declared before
// this script tag, otherwise it will log an error:
// "Uncaught ReferenceError: MyFunction is not defined"
MyFunction();
</script>
#endsection
In this solution, the function will be called right after the browser loads this piece of html, but other parts of the html may not be loaded yet.
2 - Put a script tag watching for the load event on document:
<script>
$(document).load(function() {
MyFunction();
});
</script>
The advantage of this method is that it will only be called after the entire page being loaded, so the order of the <script> tags doesn't matters (except that the jquery call must be after the jquery script tag.
IMHO is better if you divide HTML Markup and scripts using 2 sections eg:
#section('content')
<!--PAGE CONTENT...-->
<div>
<h1> Something ... </h1>
<select name="sel"></select>
</div>
<script type="text/javascript">
function MyFunction(){
obj = document.forms[0].sel;
for (i=0; i<23; i++) {
//A similar condition to onload() event.
}
}
</script>
#endsection
#section('script')
MyFunction();
// every script here will run onload
#endsection
and in your layout place both sections
<main class="container">
<section id="content">
#yield('content')
</section>
</main>
<script type="text/javascript">
$(function(){
#yield('script')
});
</script>
Or, if you don't want to use jQuery and go for the native approach, you can use:
document.addEventListener("DOMContentLoaded", function(event) {
// do your stuff here
});
Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this.
I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology.
jqueryfunctions.js:
function someFunction() {
// do.something;
}
index.html:
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="jqueryfunctions.js"></script>
</head>
<body>
<script>
someFunction();
</script>
</body>
</html>
Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction().
The console error I'm getting is "returnedMessage() is not defined".
$(function(){
var timer = null;
function appendmessageBox() {
$('body').append('<div id="messageBox" class="datamessagebox"> </div> ');
}
// just before body tag.
appendmessageBox();
// makes MessageBox Disappear on MouseOver
$('#messageBox').on('mouseover click', function(){
$(this).fadeOut(300);
});
function returnedMessage(message) {
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
$( '#messageBox' ).css('display', 'inline-block');
timer = setTimeout(function(){
$( '#messageBox' ).fadeOut( 499 );
}, 5000);
$( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 );
$( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 );
setTimeout(function(){
$( '#messageBox > msg:first-of-type' ).remove();
}, 5999);
}
// This test message bellow works correctly.
returnedMessage('hello world - test 1');
});
EDIT:
you should define your function like so:
var someFunction = function() {
// do something
}
Or like so
function someFunction() {
// do something
}
But always use the function word. More information on function definition in Javascript.
More about JS file import
Javascript code is inserted between <script> tags in an HTML file
<script>
console.log("Hello World!");
</script>
You usually place those script tags inside the <head> tag. However it's recommended you put them after your <body>. This way you allow the DOM to load before you run your JS script. This is important for exemple when you want to select elements in the DOM. If you put the JS code before the actual HTML that creates this element, then JS will not find the element you would be looking for because it doesn't yet exist.
Now it's not really efficient to work with script in your HTML code so it's helpful to write JS in .js files and then import them in you HTML file like you would for a CSS file. Use the <script> to do so:
<script src="myScript.js"></script>
You can use multiple <script> tags to pull in multiple JS files. But you need to be careful of the order you write them. For instance you have a functions.js file that holds all your functions, and a menu.js that handles the menu on your application. You're using functions from the code functions.js in menu.js so you need to import the files in this order:
<script src="functions.js"></script>
<script src="menu.js"></script>
First declared, first loaded.
You can write own function like this:
Here you can see simple example: https://jsbin.com/munowupipo/edit?html,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a Function in jQuery</title>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined the function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Me</button>
</body>
</html>
Maybe you want to take the function on document is ready, so you must to write:
<script>
$(document).on("ready", function() { yourfunction(); });
</script>
So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.
I'm writing java script code in script tag in head like:
<head>
<script language="javascript">
object o = new object({....});
</script>
</head>
and trying to use object a in body tag
<body>
<script>
alert(o.value);
</script>
</body>
how can i access object from body???
is their any alternatives?
<head>
<script language="javascript">
var o = new Object();
o.value="a"
</script>
</head>
<body>
<script>
$(document).ready(function()
{
alert(o.value)
});
</script>
</body>
In this case var a is accessible in complete application, but one thing you need to make sure if you are using external JS files then it must be loaded when you using the variable. try onload function to assure JS is loaded and ready to use in body:
window.onload = function ()
{
alert(a);
}
Since your variable is declared outside any functions it can be accessed from anywhere in your document from the same script block or from a seperate script block like in your example. it can even be accessed from html event-attributes like this (note that its better to attach events to html elements using using js):
<button onclick="alert(a);">Click this button to open an alert!</button>
setup_account ui-mobile-viewport ui-overlay-c
When a page i make loads like this:
var location = location.href+"&rndm="+2*Math.random()+" #updatecomment0>*"
$("#updatecomment0").load(location, function(){});
I have multiple scripts running on the updatecomment0 div:
<div id="updatecomment0">
<div id="javascript1">hi</div>
<div style="float:right;" class="javascript2">delete</div>
</div>
I don't know how to make this other JavaScripts run after page load.
Can someone please tell me how to with this.
Thank you
Use $(document).ready().
Use jQuery, you can do this very easily.
jQuery(document).ready(function(){
alert('Your DOM is ready.Now below this u can run all ur javascript');
});
Here is a sample layout for you
<script type="text/javascript">
$(document).ready(function(){
/// here you can put all the code that you want to run after page load
function Javascript1(){
//code here
}
function Javascript2(){
// code here
}
$("#btnOK").live('click',function(){
// some codes here
Javascript1();
Javascript2();
});
});
</script>
<div id="MyDiv">
<input type="button" id="btnOK" value="OK"/>
</div>
write code inside ready
jQuery(document).ready(function(){
// write here
});
suggestion : use live or bind
Unless you need javascript to do something before the page is loaded, add your scripts to the bottom om the html document, just before the body end tag.
The page will load faster, and you can do whatever you need to, right in the js file, without the document ready functions.
If the scripts is the last to load, the DOM is already guaranteed to be "ready".
$(window).load(function() {
// code here
});
$(document).ready() is all you needed.
You can make JavaScript wait for a specified time using the setTimeout method:
.setTimeout("name_of_function()",time_in_millis);
I hope this can help you too, I had a similar issue and I fixed it by calling the following just after loading the content in the page (like after an AJAX request for a page to be shown inside a div):
(function($) {
$(document).ready(function() {
// your pretty function call, or generic code
});
}(jQuery));
Remember to not call this in the document you load, but in the function that load it, after it as been loaded.
Using vanilla Javascript, this can done thusly:
<html>
<head>
<script type="text/javascript">
// other javascript here
function onAfterLoad() { /*...*/ }
// other javascript here
</script>
</head>
<body>
<!-- HTML content here -->
<!-- onAfterLoad event handling -->
<div style="display:none;"><iframe onload="onAfterLoad();"></iframe></div>
</body>
</html>