How to use java script code for two or more buttons

var element = document.getElementById('text'); document.getElementById("wedding").onclick = function(){ element.style.position = "absolute"; element.style.left = '-450px'; element.style.top = '-260px'; element.style.zoom = 0.8; element.style.MozTransform = 'scale(0.8)'; element.style.WebkitTransform = 'scale(0.8)'; } 

I need to use the above code for two buttons. so I am changing this code as shown below, but it does not work. How can i do this.

 var element = document.getElementById('text'); document.getElementById("wedding divorce").onclick = function(){ element.style.position = "absolute"; element.style.left = '-450px'; element.style.top = '-260px'; element.style.zoom = 0.8; element.style.MozTransform = 'scale(0.8)'; element.style.WebkitTransform = 'scale(0.8)'; } 
+4
source share
2 answers

If you need to run the same function for different elements, call the name of the function, not the imoementation function:

 document.getElementById("wedding").onclick = lalala; document.getElementById("divorce").onclick = lalala; //inside you can use `this` ( notice we didnt pass [this] , it is done automatically) function lalala() { this.style.position = "absolute"; this.style.left = '-450px'; this.style.top = '-260px'; this.style.zoom = 0.8; this.style.MozTransform = 'scale(0.8)'; this.style.WebkitTransform = 'scale(0.8)'; } 

After cleaning the OP

 var e=document.getElementById("text") document.getElementById("wedding").onclick =function (){ lalala(e) }; document.getElementById("divorce").onclick =function (){ lalala(e) }; function lalala(elm) { elm.style.position = "absolute"; elm.style.left = '-450px'; elm.style.top = '-260px'; elm.style.zoom = 0.8; elm.style.MozTransform = 'scale(0.8)'; elm.style.WebkitTransform = 'scale(0.8)'; } 
+5
source
 document.getElementById("btn1").onclick = apply_style(); function apply_style(){ document.getElementById("my_div").className="my_css_class"; } In your css: .my_css_class{ position = "absolute"; left = '-450px'; top = '-260px'; transform: scale(0.8); -ms-transform: scale(0.8); /* IE 9 */ -webkit-transform: scale(0.8); /* Safari and Chrome */ } 
+1
source

Source: https://habr.com/ru/post/1495077/


All Articles