Document.body in Opera - javascript

I've got a problem with retrieving link to the body tag. I've tried:
document.body, unfortunately it is null
search body by tagName while enumerating childs of document, it's found only the head tag :(
document.getElementsByTagName, return undefined
I'm trying to get link to the body tag in onload event handler. This is a HTML code of the page:
<html>
<head>
<title>Some page</title>
<script src="/adv.js" type="text/javascript"></script>
</head>
<body>
This is text
</body>
</html>
Here the source code of adv.js:
(function () {
var myRandom = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var myFunction = function () {
var newScriptAddr = '/adLoader.js?r=' + myRandom(1,1000000);
var fileref = document.createElement('script');
if (typeof fileref != "undefined")
{
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", newScriptAddr);
document.getElementsByTagName("head")[0].appendChild(fileref);
}
};
if (window.onload)
{
var currOnLoad = window.onload;
window.onload = function () {
currOnLoad();
myFunction();
};
}
else
window.onload = myFunction();
}) ();
Source code of adLoader.js:
(function () {
var mainCnt = document.createElement('div');
mainCnt.appendChild(document.createTextNode('The text'));
var _body = document.body;
if (!_body)
{
var htmlTag = document.documentElement;
for(var i = 0; i < htmlTag.childNodes.length; i++)
{
if (htmlTag.childNodes[i].nodeName.toLowerCase() == 'body')
{
_body = htmlTag.childNodes[i];
break;
}
}
}
if (!_body)
_body = document.getElementsByTagName('BODY') [0];
if (!_body)
_body = document.getElementsByTagName('body') [0];
if (_body)
_body.appendChild(mainCnt);
else
alert('WTF!!');
}) ();
Browser is Opera 11.10 OS Ubuntu Linux. Is there way to get this link? My aim is to add div with position:fixed to the body tag.

myFunction() doesn't return a function, so you are assigning undefined to window.onload. You probably mean window.onload = myFunction;
Anyway, as written at the moment, the code runs immediately and the body element hasn't been reached.

if the js code in head tag and the query the body tag before onload event, null should be got while browser just reading the head.

Related

javascript - replace text with tags

i do not know much about javascript searched long, but didn't get the reslut i need.
i want to replace on page load this
<p>---SOMERANDOMTEXT:::</p>
with
<strong>SOMERANDOMTEXT</strong>
played with this an many other snippets..
<script type="text/javascript">
window.onload = function() {
function myscript() {
input = '---';
output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
}
</script>
Here is the fast and fool proof way of replacing <p> tags with <strong> tags:
var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
var strong = document.createElement('strong'),
p = ps[i];
while (p.firstChild) {
strong.appendChild(p.firstChild);
}
p.parentNode.insertBefore(strong, p);
p.parentNode.removeChild(p);
}
If you need to change the text accordingly, place something like that in the while loop:
if (p.firstChild.nodeType === 3) {
p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}
DEMO: http://jsfiddle.net/5m9Qm/1/
You need to call your myscript function like this -
window.onload = function() {
myscript();
}
function myscript() {
var input = '---';
var output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
You are declaring a function myscript but never invoking it. Try this (untested) code:
<script>
window.onload = function(){
var p = document.querySelector('p');
var strong = document.createElement('strong');
strong.innerHTML = 'replaced';
p.parentNode.replaceChild(strong,p);
})
</script>
Note this requires modern browsers.
You can use a regex.
Try:
output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');
DEMO

Where to Specify Java Script in a asp:content page?

I had a html page where I was using java script to collapse and expand Gridview. However, I had to switch to a asp:content page(part of a master page) where I don't have head tag.
I tried specifying the java script inside the asp:content but it is not working.
Also, I tried specifying itmy master page still its not working.
How to deal with it any ideas?
Here is the script.
<script type="text/javascript">
function collapseExpand(obj) {
var gvObject = document.getElementById(obj);
var imageID = document.getElementById('image' + obj);
if (gvObject.style.display == "none") {
gvObject.style.display = "inline";
imageID.src = "~/ims/Images/bullet_toggle_minus.jpg";
}
else {
gvObject.style.display = "none";
imageID.src = "~/ims/Images/bullet_toggle_plus.jpg";
}
}
</script>
You can specify script at any place in your page. As soon as browser sees script tag it executes script inside it.
But in this case I think you should execute your code inside window.onload event handler because you need to wait until you markup is loaded and then you need to call your function. For example:
<script type="text/javascript">
window.onload = function(){
function collapseExpand(obj) {
var gvObject = document.getElementById(obj);
var imageID = document.getElementById('image' + obj);
if (gvObject.style.display == "none") {
gvObject.style.display = "inline";
imageID.src = "~/ims/Images/bullet_toggle_minus.jpg";
}
else {
gvObject.style.display = "none";
imageID.src = "~/ims/Images/bullet_toggle_plus.jpg";
}
}
collapseExpand("yourOfYourElement");
}
</script>
Or you can register calling your function after some event raises. For example:
document.onclick = function(){
collapseExpand("yourOfYourElement");
}

Manipulating HTML in Javascript

I am trying to manipulate the text that is already inside the div and replace it with another strings from JavaScript, creating a basic animating effect by replacing particular character from strings present inside the div element, more precisely position based replacement of string. However when I wrote down the following code it doesn't work. What I wanted to do is that store the original text in one variable and when the dom replacement of text occurs then setting certain interval replace by the old text and again replace by the new randomize text creating text replacement animation in certain position of the text.
code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text = document.getElementById("text").innerText;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
</script>
</head>
<body>
<div id="text">Hello World!</div>
</body>
</html>
So in order to make it work for a while I used the original string as
setTimeout(function(){
text.innerHTML = "Hello World!";
},200);
Which is not possible as the text in page might have been generated dynamically. When I did run the first code it says innerText of Null.
The exact error it throws is:
Uncaught TypeError: Cannot read property 'innerText' of null
What does that mean, because text and element is there why can't it grab the text from dom?
Cannot read property 'innerText' of null
Your problem is being cause because you're getting #text before it is defined.
var old_text = document.getElementById("text").innerText;
You should include this in your window.onload function as it will exist then.
Uncaught ReferenceError: flag is not defined
Once you do that you will receiving another error:
Uncaught ReferenceError: flag is not defined
For the line:
flag = flag+1;
This is because you have not defined your flag variable, this can be fixed by defining var flag; at the top of your first.
Demo
jsFiddle
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
var flag = 0;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var counter = Math.floor(Math.random()*document.getElementById("text").innerText.length);
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
flag = flag+1;
}, 350);
}
window.onload = main;
Error in Firefox
With the above code we're still receiving the original error in Firefox. This is because Firefox doesn't implement innerText. This can be fixed by using either .textContent or .innerHTML.
jsFiddle
old_text = document.getElementById("text").textContent;
var counter = Math.floor(Math.random()*document.getElementById("text").textContent.length);
// or
old_text = document.getElementById("text").innerHTML;
var counter = Math.floor(Math.random()*document.getElementById("text").innerHTML.length);
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
Just get rid of flag and counter. Initialize old_text in the onload listener.

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Assign onchange to an object and pass a parameter

So I have the following JavaScript:
<script language=JavaScript>
function reload(form){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;
</script>
But then it keeps on reloading itself constantly. Which is expected. But how can I assign reload and pass a function instance to it?
I could do:
<script language=JavaScript>
function reload(){
var form = document.getElementById("myform");
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
document.getElementById("id_profile").onchange = reload;
}
window.onload = init;
</script>
But what if I have more forms? Or I let say I want to reuse reload on multiple pages with different form names.
I would like to avoid setting onchange in the HTML tag though:
onchange="reload(this.form)"
If this is possible at all?
Thanks!
But what if I have more forms?
You can assign the same function to all the profile elements in the forms, and reference the element that received the change event inside the function using this.
<script type="text/javascript">
function reload(){
// In here, "this" is the element that received the event
var val = this.options[ this.options.selectedIndex ].value;
self.location='?profile=' + val ;
}
function init(){
var len = document.forms.length;
while( len-- ) {
document.forms[ len ].profile.onchange = reload;
}
}
window.onload = init;
</script>
You can make a function that returns a function (a closure) for the reload function.
function reload(form){
return function(){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;

Categories

Resources