Put Javascript function inside the onclick

3

So it's a bit silly doubt but I need it a lot ... I have a Javascript function inside a buttom in this example it calls the loadDoc () function. but I'd like to put the function directly inside the onclick.

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>

Source: link

    
asked by anonymous 09.12.2016 / 00:16

2 answers

5

Using anonymous function

<input type="button" value="anonymous function" onclick="(function(){
console.log('ok');
console.log('ok2');
})()">

In this snippet I just wanted to show that it is possible to apply line breaks, making the code more readable.

Implementing for your specific case:

<input type="button" value="anonymous function" onclick="(function(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send();
    })()">

In the case of sending parameters to the function

In your case there is no passing of parameters. If you want to pass parameters to the function, see this example

<input type="button" value="anonymous function" onclick="(function(v){
console.log(v);
console.log('ok2');
})('ok')">

Observations

Obviously, any web developer who understands the basics is aware of good practices and semantics, however, situations can occur where there is no way to follow a correct semantics or even such issues get out of context. It is not here to judge whether what you want to do is right or wrong, because the business model, the reasons, the reasons or the circumstances are not explicit.

    
09.12.2016 / 01:03
4

You do not have to put a whole script inside a single button

  • Is it possible? The answer is yes
  • Is it recommended? The answer is no

I will explain later why it is not recommended.

Inline example

While not being recommended, I'll give you an example, to resolve you need to change the quotes to "single quotation marks" (apostrophes):

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('demo').innerHTML = this.responseText; } }; xhttp.open('GET', 'ajax_info.txt', true); xhttp.send();">Change Content</button>
</div>

</body>
</html>
  

Please note that the link page is not working due to a browser security lock, is w3schools.com's fault and not the script itself.

What is preferable

It is best to move every script into a .js file, regardless of model, circumstances; anyway you can avoid all this using DOM and no one is judging, this is a guidance on how to avoid problems and show that much is possible.

Using everything in .js files will bring you advantages like:

  • Resource Cache
  • Code reuse
  • Decreased HTML
  • Avoid obstructing HTML
  • Easy to organize

For example, create a file named app.js and place this content:

function ready(callback)
{
    if (/^(interactive|complete)$/i.test(doc.readyState)) {
        callback();
    } else {
        doc.addEventListener('DOMContentLoaded', callback);
    }
}

function loadDoc(url, callback, error)
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        callback(this.responseText);
    } else if (error) {
        error(this.status);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

//Equivale ao $.ready do jQuery
ready(function() {
    var botao1 = document.getElementById("botao1");
    var botao2 = document.getElementById("botao2");

    botao1.onclick = function() {
        loadDoc("ajax_info1.txt", function(resposta) {
            document.getElementById("demo").innerHTML = resposta;
        });
    };

    botao2.onclick = function() {
        loadDoc("ajax_info2.txt", function(resposta) {
            document.getElementById("demo").innerHTML = resposta;
        });
    };
});

And the html should look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Exemplo</title>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
      <div id="demo"></div>

      <button id="botao1">Testar 1</button>
      <button id="botao2">Testar 2</button>
</body>
</html>

Looks much less polluted

    
09.12.2016 / 00:30