How to call functions with the onclick event? - Javascript

3

<script>
        function pausaplay(){
  document.getElementById('demo45').play();
  document.getElementById('demo14').pause();
}
</script>
<input value="Mirar Havana" onclick="if(this.parentNode.getElementsByTagName('div')[0].style.display != ''){this.parentNode.getElementsByTagName('div')[0].style.display = '';this.value = 'Mirar Havana';}else{this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'Mirar Rockabye';}" type="button">

I've tried it this way:

<script>
function pausaplay(){
if(this.parentNode.getElementsByTagName('div')[0].style.display != ''){this.parentNode.getElementsByTagName('div')[0].style.display = '';this.value = 'Mirar Havana';}else{this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'Mirar Rockabye';}
  document.getElementById('demo45').play();
  document.getElementById('demo14').pause();
}
</script>

<input value="Mirar Havana" onclick="pausaplay()" type="button">

but I do not think so, I'm learning javascript so far, that's why I have many doubts ... thanks for your respect

    
asked by EDITOR DE HTML 16.01.2018 в 20:41
source

2 answers

3

If I understood correctly, the way you did it is correct.

<input value="Mirar Havana" onclick="pausaplay();" type="button">

Inside the onclick you add the name of your function to execute, obviously you will have to link your javascript file to the html by:

<script src="nombre-de-tu-archivo.js"></script>

Or have written your code js as you did.

    
answered by 17.01.2018 / 00:04
source
1

To know that your code function is correct and your function is called you can use the browser's JS console and the associated functions. If the code is correct, it will be executed, if there are errors, it indicates it.

Example:

HTML:

<p onclick="test()">Clic aquí</p>

JS:

function test() {
    console.log( "Ejecutando función test()" );
}

Result (in console):

Ejecutando función test()

If you have several functions that you want to associate with the same event, for example a click on a certain element of the page, it is enough to make calls to those functions within one that is called by the event. For example:

HTML:

<p onclick="test()">Clic aquí</p>

JS:

function test() {
    console.log( "Ejecutando función test()" );

    //Llamada a otras funciones:
    rojo();
    verde();
}

function rojo() {
    console.log( "Ejecutando rojo()" );
}
function verde() {
    console.log( "Ejecutando verde()" );
}

Result (in console):

Ejecutando función test()
Ejecutando rojo()
Ejecutando verde()
    
answered by 17.01.2018 в 00:17