How to apply a function to multiple objects? (Pure Javascript)

4

For example, I have div inside a variable obj

 obj = document.getElementById("objeto");

I want a function to be applied to it, so

 window.onload = function(){
    window.onclick = function (){
       obj = document.getElemntById("obj");
       obj.ver();
    }
    function ver(){
       this.style.backgroundColor = "#333333";
    }
 }  

How could I make this application work?

My full code, abbreviated:

    <script>        
    HTMLElement.prototype.mover = function(){

        movendo = false;
        valor = 0;
        calc = 0;
        resto = 0;
        this.onmousedown = function(e){                
            movendo = true;
            valor = e.pageX + document.body.scrollLeft;     
            calc = valor - this.offsetLeft;
            resto = this.offsetWidth - calc;

            valor2 = e.pageY + document.body.scrollTop;     
            calc2 = valor2 - this.offsetTop;
            resto2 = this.offsetHeight - calc2;

            this.style.cursor = "move";

        };            
        window.onmouseup = function(){

            movendo = false;
            this.style.cursor = "pointer";        
        };

       window.onmousemove = function(e){
            if( movendo == true ) {

                this.style.left = (e.pageX + document.body.scrollLeft) - this.offsetWidth + resto + "px";
                this.style.top = (e.pageY + document.body.scrollTop) - this.offsetHeight + resto2 + "px";

            }
        };
    }

    window.onload = function(){            
        obj = document.getElementById("obj");
        obj.mover();            
    }         
    </script>
    
asked by anonymous 10.07.2014 / 18:42

1 answer

5

To do this you have to extend prototype and add this method to the elements.

Example: link

HTMLElement.prototype.ver = function() {
    this.style.backgroundColor = "#333333";
}

window.onload = function () {
    window.onclick = function () {
        obj = document.getElementById("obj");
        obj.ver();
    }
}

Using the word prototype accesses the prototype of all elements and this method is available in all elements. Be careful not to write over existing methods as this tool is very powerful.

    
10.07.2014 / 18:49