I have my code here.
// HTML Code
<div class="article"></div>
// jQuery
$('.article').append('<a href="" class="toggle">Toggle div</a>');
Is it possible to use that newly created href link and toggle a div like this:
// jQuery
$('.toggle').click(function() {
$('.article').toggle('slow');
});
I have tried the above with no luck. I just get redirected to index page.
Don’t use
click(): it’s deprecated and wouldn’t work even if it weren’t. Useon():Also, change your
atag to<a href="javascript:void(0)" class="toggle">Toggle div</a>.As to the reason why
on()works andclick()doesn’t, you need to read jQuery’s documentation. In short, the click event has been bound to an element on the page; this scope does not cover future elements that are added to the DOM.On(), however, is a delegated event: