En javascript, on peut lancer une fonction quand on clique sur un élément HTML.
Pour lancer une fonction quand on clique sur un élément HTML, il suffit d'ajouter l'attribut onclick dans une balise HTML (<p>, <img>, <a> etc.) et d'y associer une fonction entre guillements, éventuellement avec un attribut entre parenthèses. La fonction est définie ailleurs, entre des balises <script>:
<balise onclick="nomDeMafonction( arguments)" > Mon texte qui réagit </balise>
<script>
function nomDeMafonctiont( argumentsDeLaFonction )
{ //définition de la fonction
}
</script>
Voici quatre exemples de paragraphes avec une fonction associée via onclic:
<p onclick="maFonctionSansArgument()"> Mon Texte Qui Réagit à une fonction sans argument </p>
<p onclick="maFonctionAvecUnArgument('1')"> Mon Texte Qui Réagit à une fonction avec un argument </p>
<p onclick="maFonctionAvecUnArgument('Argument qui change mais la même fonction')"> Mon Texte Qui Réagit à la même fonction avec un argument </p>
<p onclick="maFonctionAvecDeuxArguments('Lauren', 'Thévin')"> Mon Texte Qui Réagit à une fonction avec deux arguments </p>
<p onclick="maFonctionAvecUnArgument(maVariable)"> Mon Texte Qui Réagit à une fonction avec un argument qui est une variable en Javascript </p>
<script>
let maVariable="Je suis une variable";
function maFonctionSansArgument( )
{ alert("Bonjour, vous n'avez pas d'argument");
}
function maFonctionAvecUnArgument( monArgument)
{alert("Bonjour, vous avez l'argument : "+ monArgument);
}
function maFonctionAvecDeuxArguments( monArgument1, monArgument2)
{alert("Bonjour, vous avez deux arguments : "+ monArgument1 + ", "+ monArgument2);
}
</script>
<!DOCTYPE html>
<html>
<body>
<p> J'ai fait le choix 1 </p>
<p> J'ai fait le choix 2 </p>
</body>
</html>
function jaiFaitLeChoix()
{ alert("J'ai Choisi !");
}
<html>
<body>
<p > J'ai fait le choix 1 </p>
<p onclick="jaiFaitLeChoix()"> J'ai fait le choix 2 </p>
<script>
function jaiFaitLeChoix()
{ alert("J'ai Choisi !");
}
</script>
</body>
</html>
<html>
<body>
<p onclick="jaiFaitLeChoix()"> J'ai fait le choix 1 </p>
<p onclick="jaiFaitLeChoix()"> J'ai fait le choix 2 </p>
<script>
function jaiFaitLeChoix()
{ alert("J'ai Choisi !");
}
</script>
</body>
</html>
<html>
<body>
<p onclick="jaiFaitLeChoix('1')"> J'ai fait le choix 1 </p>
<p onclick="jaiFaitLeChoix('2')"> J'ai fait le choix 2 </p>
<script>
function jaiFaitLeChoix( monChoix)
{ alert("J'ai Choisi ! "+ monChoix);
}
</script>
</body>
</html>