how do I automatically execute javascript? - javascript

how do I automatically execute javascript?
I know of <body onLoad="">, but I just thought maybe there is another way to do it?
html:
<html><head></head><body><div id="test"></div></body></html>
javascript:
<script>(function(){var text = document.getElementById('test').innerHTML;var newtext = text.replace('', '');return newtext;})();</script>
I wanna get the text within "test", replace certain parts, and then output it to the browser.
Any ideas on how to do it? I'd appreciate any help. Thanks.

If you don't want to use <body onload> which is good choice in terms of obtrusive javascript, you can separate that and put you code like this:
window.onload = function(){
// your code here
};
Alternative:
Place your javascript code at the bottom of the page.

Place the script at the bottom of the page, outside the closing body tag..

It's REALLY easy! If you have a script in your "head" block, with no function id, it will run automatically as soon as the web page loads. For example:
<head>
<meta charset="UTF-8">
<title>Redirection to www.mywebsite.org</title>
<!-- This script initiates an automatic web page redirection, as the page is loaded -->
<script type="text/javascript">
window.location = "http://www.mywebsite.com/"
</script>
</head>

If you don't want to use jQuery, use native window.onload method:
<script type="text/javascript">
function ReplaceText() {
document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/abc/g, "def");
}
window.onload = ReplaceText;
</script>
Used on the code:
<div id="test">abc abc</div>
Will give this output:
def def

A quick way, if you just want to debug, would be move what you want to execute outside of a function.
<script type="text/javascript">
var text = document.getElementById('test').innerHTML;
var newtext = text.replace('', '');
alert(newtext);
</script>
NB. I'm not sure what you hope to achieve with text.replace('', '') ?

Related

Function didn`t render_template Flask [duplicate]

I have an HTML page with a typical structure:
<html>
<head>
<script src="..." ></script>
<style>...</style>
</head>
<body>
content
</body>
<script>
var success_callback = function(data) {
// REPLACE PAGE CONTENT & STRUCTURE WITH "data"
}
ajax(url, params, success_callback);
</script>
</html>
Do you think it is possible ? I've already tried to give the html tag an id and doing $(id).replace(data); with no success.
Don't ask me why, but that is what I need (I'm working with a special "mashup builder" site... it is a long story).
EDIT : I forgot to say that scripts in the received content have to be executed, even external scripts included using <script src="...">.
The simplest way is to set the new HTML content using:
document.open();
document.write(newContent);
document.close();
try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load
Here's how to do it in Prototype: $(id).update(data)
And jQuery: $('#id').replaceWith(data)
But document.getElementById(id).innerHTML=data should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.
You could try doing
document.getElementById(id).innerHTML = ajax_response
the simplest way is
$("body").html(data);
Can't you just try to replace the body content with the document.body handler?
if your page is this:
<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>
Just use the document.body to replace the body.
This works for me. All the content of the BODY tag is replaced by the innerHTML you specify.
If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.
An example with javascript scripting inside it:
<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>
This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.
Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.
I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>

HTML and JavaScript in separate files - newbie alert

OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.

HTML - Alert Box when loading page

i'm using HTML code and i wan't to show un Alert Message or alert box, i don't know what it is called, but a message with a "OK" button.
i want to show this alert when the page is loaded.
How do i do this?
And how to do this with a title in the Alert box?
Do I need JavaScript? if no, How to do this without javascript?
Jonathan
Yes you need javascript. The simplest way is to just put this at the bottom of your HTML page:
<script type="text/javascript">
alert("Hello world");
</script>
There are more preferred methods, like using jQuery's ready function, but this method will work.
You can use a variety of methods, one uses Javascript window.onload function in a simple function call from a script or from the body as in the solutions above, you can also use jQuery to do this but its just a modification of Javascript...Just add Jquery to your header by pasting
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
to your head section and open another script tag where you display the alert when the DOM is ready i.e. `
<script>
$("document").ready( function () {
alert("Hello, world");
});
</script>
`
This uses Jquery to run the function but since jQuery is a Javascript framework it contains Javascript code hence the Javascript alert function..hope this helps...
you need a tiny bit of Javascript.
<script type="text/javascript">
window.onload = function(){
alert("Hi there");
}
</script>
This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.
If you use jqueryui (or another toolset) this is the way you do it
http://codepen.io/anon/pen/jeLhJ
html
<div id="hw" title="Empty the recycle bin?">The new way</div>
javascript
$('#hw').dialog({
close:function(){
alert('the old way')
}
})
UPDATE : how to include jqueryui by pointing to cdn
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
For making alert just put below javascript code in footer.
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You need to also load jquery min file.
Please insert this script in header.
<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
<script type="text/javascript">
window.alert("My name is George. Welcome!")
</script>
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You can try this.
$(document).ready(function(){
alert();
$('#rep‌​ortVariablesTable tbody').append( '<tr><td>lll</td><td>lll</td></tr>');
});

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

Categories