Evento onclick en Javascript

Usando el siguiente div:

<div id=»probando»
style=»display:block;height:50px;width:50px;»
onclick=»myFunction()»>
Prueba con javascript
</div>

Vamos a realizar algunos ejercicios con el evento onclick de javascript.

 

«Herramientas»:


– Obtener un elemento por su ID: document.getElementById(«id») en cada ejemplo.
– Un poco de HTML (el div anterior), con algo de estilo y el evento onclick asociado a una función que hemos llamado myFunction
– Para el primer ejemplo, obtenemos las medidas del elemento con .offsetWidth y .offsetHeight
– Para el segundo, establecemos el color con .style.color
– Para el primero y el tercero, establecemos las medidas con .style.width y .style.height


1- Ampliar y reducir según tamaño


<script>

function myFunction() {

var ancho = document.getElementById(«probando»).offsetWidth;
var alto = document.getElementById(«probando»).offsetHeight;

if (ancho<100) {
document.getElementById(«probando»).style.width = «100px»;
document.getElementById(«probando»).style.height = «100px»;
} else {
document.getElementById(«probando»).style.width = «50px»;
document.getElementById(«probando»).style.height = «50px»;

}
}

</script>


2- Cambiar color de fondo


<script>
function myFunction() {
document.getElementById(«probando»).style.color = «red»;
}
</script>


3- Establecer tamnaño

<script>
function myFunction() {
document.getElementById(«probando»).style.width = «100px»;
document.getElementById(«probando»).style.height = «100px»;

}
</script>

Write a Reply or Comment

Your email address will not be published.