user317005
user317005

Reputation:

how do I automatically execute 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.

Upvotes: 13

Views: 103945

Answers (5)

user2993258
user2993258

Reputation: 91

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>

Upvotes: 4

Piotr Rochala
Piotr Rochala

Reputation: 7781

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

Upvotes: 1

Dan Diplo
Dan Diplo

Reputation: 25359

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('', '') ?

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382909

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.

Upvotes: 20

Sky Sanders
Sky Sanders

Reputation: 37104

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

Upvotes: 7

Related Questions