Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
Eventlistener is fired on whole document

I have an issue in my Javascript code with the eventlistener. The Eventlistener (click) is firing over the whole document and not only on the specific element.

external file:

function $(selector){
    const self = {
        element: document.querySelector(selector),
        on: (event, callback) => {
            document.addEventListener(event, callback)
        }
    }
    return self;
}

function coy(){
    let _this = this;
    
    
    this.Text = (element) => {
        $(element).on('click', function(){
            alert(document.getElementById(element).value);
        });
    }   
}

On page

<input type="text" id="text"/>
coy.Text('text');

Hope somebody can help me.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What a strange question.

  1. You are adding the event listener to the document on line 5
  2. The constructor function doesn't follow naming conventions. Also, why do you want to preserve this that doesn't have the text() method?
  3. The method isn't static, so you have to instantiate Coy before you are able to call text() on it.
  4. You are passing the argument of "text" to the coy.text() method, but it seems that it's expecting a selector because it uses that argument in a call of the $ function.
  5. You make some sort of weird bootleg jQuery but then right after you define that function, you still decide to use document.querySelector

const $ = (selector) => {
    return {
        element: document.querySelector(selector),
        on: function (event, cb) {
            this.element.addEventListener(event, cb);
        },
    };
};

class Coy {
    constructor() {
        this.text = (element) => {
            $(element).on('click', () => alert($(element).element.value));
        };
    }
}

const coy = new Coy();

coy.text('input[type="text"]');
<input type="text" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda