Error calling 2 javascript functions at the same time

0

Hello, I need to call these two separate functions as this is the only code that only one works how do I both work?

<script type="text/javascript">

    window.onload = function() {

        if ('a' == 'a')

        {
           document.getElementById("nomeprodut").innerHTML = "Altera nome do produto";
        } 

    }
</script>

<div id="nomeprodut"></div>


<script type="text/javascript">

    window.onload = function() {

        if ('b' == 'b')

        {
           document.getElementById("b").innerHTML = "grghgh";
        } 

    }
</script>

<div id="b"></div>
    
asked by anonymous 16.02.2017 / 17:47

3 answers

2

You can add more than one function to the same event, and it will run once in the onload case, but will perform all functions in the order that you add using addEventListener . Documentation here: link

Basically, you do the following:

window.addEventListener("load",function(event) {
    if ('a' == 'a') {
    document.getElementById("nomeprodut").innerHTML = "Altera nome do produto";
  }
},false);

then:

window.addEventListener("load",function(event) {
  if ('b' == 'b') {
    document.getElementById("b").innerHTML = "grghgh"; 
  }
},false);

And so on, you can add other listener to the load event.

    
16.02.2017 / 18:33
2

I suggest using the DOMContentLoaded event, which runs after all content is loaded. Here's an example:

<script type="text/javascript">
    function a() {
        alert('a');
        if ('a' == 'a')
        {
           document.getElementById("nomeprodut").innerHTML = "Altera nome do produto";
        } 
    }
</script>
<div id="nomeprodut"></div>

<script type="text/javascript">

    function b() {
        alert('b');
        if ('b' == 'b')

        {
           document.getElementById("b").innerHTML = "grghgh";
        } 
    }

document.addEventListener('DOMContentLoaded', function(){
    a();
    b();
});

</script>
<div id="b"></div>
    
17.02.2017 / 00:13
1

Put everything inside a onload only, thus:

<div id="nomeprodut"></div>
<div id="b"></div>

<script type="text/javascript">
window.onload = function () {
  if ('a' == 'a') {
    document.getElementById("nomeprodut").innerHTML = "Altera nome do produto";
  }
  if ('b' == 'b') {
    document.getElementById("b").innerHTML = "grghgh"; 
  }
}
</script>
    
16.02.2017 / 17:52