Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
JS stop working after jquery .load content

Please help me to understand why js stop working after .load THE SAME CONTENT in div.

<main class="container">
    <div id="reload_div">
        <div id="color_div" style="width:100px;height:100px; background:red; margin-bottom: 100px">
            orig
        </div>
        <button id="make_it_green" type="submit" class="btn btn-sm btn-primary">
            make it green
        </button>
    </div>
    <button id="reload_btn" type="submit" class="btn btn-sm btn-primary" style="margin-top:20px">
        reload
    </button>
</main>

<script>
$("#make_it_green").click(function(){
  $("#color_div").css("background","green")
}); 

$("#reload_btn").click(function(){
  $("#reload_div").fadeTo(300,0, function () {
    $("#reload_div").load ("reload.php", 
    {  }, function () {
        $("#reload_div").fadeTo(300,1, function () {
        });
    });
  });
}); 
</script>

After .load the same content in "reload_div" #make_it_green button stop working! Why?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you run your code as you have posted it, the event handler is added to the make_it_green button.

Once you load the new content with jQuery the element to which the handler was attached no longer exists, so the event handler no longer exists. You load a new element with the same name, but there's no event handler attached unless you attach the event handler again.

Alternatively, attach the event handler to the containing div and delegate the event handling.

$("#reload_div").click(function(e){
        e.preventDefault();

        // Check the id of the original target element. If it's 
        // our button, change the colour.
        if (e.target.id === "make_it_green") {
            $("#color_div").css("background", "green");
        }
    });

See this page on MDN for a detailed discussion of event delegation

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda