I try to use some 'dijit' widget from script, for example to change content or to connect event.
For this purpose I try to use 'data-dojo-id' attribute in html, which (as I understood) creates global object of type 'data-dojo-type' and name 'data-dojo-id'.
But I got errors... What I do wrong?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dojo test</title>
</head>
<body>
<div id="myDivId"
data-dojo-type="dijit.layout.ContentPane"
data-dojo-id="myDojoId">
Hello Everyone!
</div>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad:true"></script>
<script type="text/javascript">
require(["dijit/dijit", "dijit/layout/ContentPane"], function(){
//myDojoId.setContent("Hello World!"); // error : myDojoId is not defined
// Even this not working:
console.log(dijit.byId("myDivId")); // undefined
console.log(dijit.byId("myDojoId")); // undefined
});
</script>
</body>
</html>
data-dojo-id and jsId (deprecated) attributes create a global object referring to that dijit.
I believe you need to wrap the lookups in a ready() call
<script type="text/javascript">
require(["dojo/ready","dijit/dijit", "dijit/layout/ContentPane"], function(ready,dijit,ContentPane){
//shouldn't be defined yet
console.log(dijit.byId("myDivId")); // undefined
console.log(myDojoId); // undefined
ready(function(){
console.log(dijit.byId("myDivId"));
//note how data-dojo-id doesn't have the lookup
console.log(myDojoId);
});
});
</script>
Related
I am using modern Javascript MyClass.js
export default class MyClass {
constructor(x) {
this.val=x? x: "Hello!"
console.log("MyClass:",x)
}
}
at my http://localhost/myfolder/mypage.htm, with the source below,
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
<script type="module" src="./MyClass.js"></script>
<script>
'use strict';
document.addEventListener('DOMContentLoaded', function(){
alert(123)
let x = new MyClass(11);
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
Why console say "Uncaught ReferenceError: MyClass is not defined"?
PS: this question is a complement for this other about using ES6+ with browser+NodeJs.
NOTE: using UBUNTU ith Apache's Localhost... Some problem with myfolder a symbolic link to real folder? at /var/www/html I used ln -s /home/user/myRealFolder/site myfolder
you need to import the module before using it
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script type="module" src="./MyClass.js"></script>
<script type="module" id="m1">
// script module is an "island", not need onload.
'use strict';
import MyClass from './MyClass.js';
let x = new MyClass(11); // we can use here...
console.log("debug m1:", x) // working fine!
window.MyClassRef = MyClass; // "globalizing" class
window.xRef = x // "globalizing" instance
</script>
<script> // NON-module global script
document.addEventListener('DOMContentLoaded',function(){
// only works after all modules loaded:
console.log("debug:", window.xRef) // working fine!
let x = new window.MyClassRef(22); // using class also here,
console.log("debug:", x) // working fine!
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
There are two ways to use an imported class:
at module scope (script m1): you can use new MyClass(), and can "globalize" instances (e.g. xRef) or the costructor's class (MyClassRef).
at global scope: to work together other libraries or with main script, use a global reference, e.g. new window.MyClassRef().
All this solution relies upon "static import"...
Optional dynamic import
You can use also import with ordinary default <script> (no type="module"), and no "onload", using this solution, instead the last script:
<script>
'use strict';
import('./MyClass.js').then(({default: MyClass}) => {
alert(123) // async block
let x = new MyClass(11);
});
</script>
See dynamic import.
My localStorage returns null, and I don't know why, the read function is not used, but just for help I put it anyway. Chrome says that it cannot ste innerHTML into null, and my troubleshooting alert info also returns null, but the code goes to the end. Any help would be useful, thank you. The cookie:
<!doctype html>
<html>
<head>
<cookie>
<script>localStorage.setItem('id',Math.floor(Math.random()*10))
</script>
</cookie>
</head>
<body>
<script>var id = localStorage.getItem('id')
alert(id)</script>
</body>
</html>
The Script:
<!doctype html>
<html>
<head>
<script>
var theId=localStorage.getItem('id')
function change(id,target){
var info = localStorage.getItem(id);
alert(info)
document.getElementById(target).innerHTML=info;
}
function read(){
var element=document.createElement('h1')
element.innerHTML='You Want To Read'
document.body.appendChild(element)
alert('debug')
}
</script>
</head>
<body>
<input type="button" value="Read" name="read_story" id="read_story"
onclick=read();change(theId,info)>
<p id='info'>initial</p>
</body>
<script>
alert('debug');
</script>
</html>
You've misinterpreted the error message.
If it can't set the innerHTML of null then you have something.innerHTML = a_value. It is the something that is null not anything to do with local storage.
In change(theId,info), info is a variable. It is a reference to the element with id="info".
You use it here: document.getElementById(target).
info (now target) gets converted into a string ("[object HTMLParagraphElement]").
There is no element with id="[object HTMLParagraphElement]", so you get null.
When you call the function, you need to pass a string, not a variable.
Chrome throws the following error:
Uncaught TypeError: Property 'js' of object function
(){d.ready.apply(null,arguments)} is not a function
While Firefox throws a TypeError: head.js is not a function
Here is my code:
<!doctype html>
<html lang="eng" ng-app="app">
<head>
<meta charset="UTF-8">
<title>{{ page_title }}</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.99/head.core.min.js"></script>
</head>
<script>
head.js({ angularJS: "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"},
{ jQuery: "http://code.jquery.com/jquery-1.10.1.min.js" },
{ internalApp: "app/js/app.js"});
head.ready('jQuery', function() {
$(document).ready(function() {
console.log('jQuery loaded successfully');
});
});
</script>
<body>
<!-- add data here -->
</body>
</html>
You have loaded the Responsive Design + Feature Detections script http://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.core.min.js and not the Asset Loader http://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.load.min.js
I just made the same mistake and found this post while looking up the answer :)
I have two scripts and I need to use script1 function in script2. Whats the best way to do it and Is there any simplification using prototype to access function in more scripts. I am using jquery.
script1
$(function(){
function process(){
// some code
}
})
script2
$(function(){
// I would like to use the process function here
}
Sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript" charset="utf-8" src="Script1.js" ></script>
<script type="text/javascript" charset="utf-8" src="Script2.js" ></script>
<script>
</script>
<BODY onload='calling();'>
</BODY>
</HTML>
Scrip1.jc
function call(){
alert("Hi i am called from script2");
}
Scrip2.js
function calling(){
call();
}
Hope this help you.
You can use javascript functions as variables. So just reread your question about the same stuff about variables - Unable to access variable
So just do so your function will be available from global scope.
Just move the function declaration outside the ready event handler, that will make it globally available.
Another idea: use objects:
var Ob = {
process: function(callback) {
callback();
}
}
script1
$(function(){
Ob.process(function(){
... // code
});
});
script 2 (do same)
$(function(){
Ob.process(function(){
... //another code
});
});
If you are using same process function (means same body content, make same thing in both script) then
var Ob = {
process: function() {
...//put code
}
}
script1
$(function(){
Ob.process();
});
script 2 (do same)
$(function(){
Ob.process();
});
I have two pages one is the main page and the another one is the inner page:
Page names: main.jsp , sidebar.jsp
I want to call the onload function on both of these pages. Is that possible. If yes How?
Below is the code for main.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# include file="/pages/common/init.jsp"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>J.C. Taylor - Broker Website</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/default.css" media="screen" type="text/css" />
</head>
<body onload="prepopulateFields();load(17);">
<s:form name="continue" id="continue_id" action="continue" method="POST" validate="true" enctype="multipart/form-data">
<div id="wrapper">
<div id="main">
<div id="sidebar">
<%# include file="/pages/common/sidebar.jsp"%>
<span class="clearIt"></span>
</div>
The sidebar.jsp is:
<body onload="setSelected();">
//Some static content here
</body>
So Basically I want is to call prepopulateFields() Javascript method which belongs to onload() event of the main .jsp page and setSelected() which belongs to onload() method of the sidebar.jsp symulatneously and separately.
I know I can call the setSelected(); method inside the prepopulateFields() method but that I dont want to do. All I want is when the page is loaded both the onload functions should be called separately.
If you have some suggestions please do let me know!
I know I am being little bit ridiculous here but if I could do that My job will be very easy.
i don't think you can call more than one onload function.
best way is to call the method from already called function
function prepopulateFields(){
if //condition which check the current page where you want other onload function
setSelected();
}
<body onload="prepopulateFields();load(17);">
</body>
You cannot nest HTML <body> elements, it would only malform HTML.
Best is to put it as a <script> at the bottom of sidebar.jsp.
<script type="text/javascript">setSelected()</script>
If you use firebug to inspect the rendered html page of main.jsp. You would see there is only one < body > element. The < body > element in your sidebar.jsp is not rendered since it will malform HTML as html or body not allowed in included jsp.
Be careful that the included file does not contain <html>, </html>, <body>, or </body> tags
The solution is:
either put your setSelected() into main.jsp body onload event if the sidebar.jsp is always loaded;
or do as BalusC suggested.
window.onload = codeAddress; should work. Here's a demo. And the full code:
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
Put the class definition in the parent jsp, and instantiate as many onloads as you need in the includes.
<SCRIPT>
// this portion was placed above the Class definition for convenience.
// make sure the Class definition gets loaded first in your code.
new OnLoad(function(){
alert("document loaded");
},100);
</SCRIPT>
...
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
</SCRIPT>