nick danvery
nick danvery

Reputation: 41

Event binding with jquery live() function

First here is the code:

HTML:

<div id="foreground">
    <button type="button" id="go">Start</button>
</div>
<div id="background">
    <p>You are on the background</p>
</div>

JS:

$(function () {
    $("#go").click(function (e) {
        var $q = $(this);
        var $vazy = $('<button type="button" id="vazy"> Vazy </button>');
        var $loc = $('<input type="text" id="placename" placeholder="Location"/>');

        $vazy.insertAfter($q);
        $loc.insertAfter($q);
        $q.hide();

        e.stopPropagation();

    });

    $("#vazy").live("click", function () {
        alert('k');
        //$("#foreground").hide();
        //$("#background").show();
    });

});

CSS:

#background {
    display: none;
}

jsFiddle...

The problem is at the line 15 where the button with the ID #vazy seems not to respond to my click event even with the live binding. Am I missing something?

Thanks for any response :)

Upvotes: 0

Views: 74

Answers (4)

vborutenko
vborutenko

Reputation: 4443

Try this

    $("body").on("click","#vazy" function () {
    alert('k');
    //$("#foreground").hide();
    //$("#background").show();
});

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74410

Your best bet: {foreground is the closest static container, use it as delegate}

$("#foreground").on("click",'#vazy', function () {...});

Upvotes: 0

Adil
Adil

Reputation: 148178

live is deprecated use on() to bind event to dynamically added elements. You can delegate event to parent of the element or document.

Live Demo

$(document).on("click", "#vazy", function () {
    alert('k');
    //$("#foreground").hide();
    //$("#background").show();
});

delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Upvotes: 1

Anujith
Anujith

Reputation: 9370

.live() is deprecated..

Try using .on():

$('body').on("click",'#vazy', function () {
    alert('k');
});

Works here

Upvotes: 2

Related Questions