blue-sky
blue-sky

Reputation: 53816

.on function not being fired

I'm attempting to use the .on event when some text is clicked. Here is my fiddle :

http://jsfiddle.net/adrianjsfiddlenetuser/zyUkd/73/

But nothing is being fired when I click 'link', I don't know why ? From reading http://api.jquery.com/on/ I don't think the data I should be passing is .connected ?

This needs to work for dynamically added elements. Here is the code from the fiddle :

<div id="myID">
    <a class="connected" >link</a>
</div>

​$(function() {

$(".connected").on('click', '.connected', function() {
    alert('fired)'
        $(".connected").append("<a>hello</a>");
});



});

​.connected {
    float: left;
    margin: 6px;
}

Upvotes: 1

Views: 49

Answers (3)

Christopher Marshall
Christopher Marshall

Reputation: 10736

Put it in a ready function, as well as fixed a syntax error on alert.

http://jsfiddle.net/zyUkd/75/

    $(document).ready(function() {

        $(".connected").on('click', function() {
            alert('fired');
                $(".connected").append("<a>hello</a>");
        });    

 });

Upvotes: 0

VisioN
VisioN

Reputation: 145398

You can use either this:

$(".connected").on('click', function() {
    alert('fired')
    $(".connected").append("<a>hello</a>");
});​

Or this:

$("#myID").on('click', '.connected', function() {
    alert('fired')
    $(".connected").append("<a>hello</a>");
});​

Note, the second variant works for dynamically added elements.

DEMO: http://jsfiddle.net/zyUkd/74/

Upvotes: 2

Adam Merrifield
Adam Merrifield

Reputation: 10407

Get rid of the seccond .connected. also your alert is written wrong.

$(function(){
        $(".connected").on('click', function() {
            alert('fired');
            $(".connected").append("<a>hello</a>");
        });
    });

Upvotes: 2

Related Questions