javascript - fadeOut dynamically loaded div using jquery -
im writing small app, , im having problems deleting (as in fading out) dynamically loaded div using jquery.
the problem presents when add new content box, if reload page , content box gets rendered not dynamically (as in database query), deletes fine(as in fade out), when div added anew, cant out.
$result = '<div class="my-music-item">'. $app['twig']->render('soundcloud-player.twig', array( 'url'=>$mix->geturl(), 'player_type'=>'artwork', 'url'=>$mix->geturl(), 'color'=>'ff0948', 'height'=>'200', 'width'=>'200' )) . '<p class="delete-mix-wrapper"><a class="delete-mix" data-mix-id="'.$mix->getid().'" data-post-to="'.$app['url_generator']->generate('delete-mix-post').'" href="javascript:;">delete</a></p>' . '</div>'; return new response(json_encode(array( 'html'=>$result, 'status'=>'true' )));
thats code creates div dynamically.
yet when click delete, nothing happens.
here comes code handles post request through js.
$('a.delete-mix').on('click', function() { var parent = $(this).closest('div.my-music-item'); $.post($(this).attr('data-post-to'), { mix_id: $(this).attr('data-mix-id') }) .done(function(data) { parent.css('background-color', 'pink'); parent.fadeout('fast'); }); });
i have been reading lot, without luck! first code looked bit differently, didnt had
.on('click', function() {
but rather was
.click(function() {
thanks in advance input!
@psl correct. common problem adding event handlers using jquery element not exist on page when js run, means event handler not bound element, , nothing happens.
if change line
$('a.delete-mix').on('click', function() { ... } )
to
$( document ).on( 'click', 'a.delete-mix', function() { ... } )
then shouldn't have trouble.
the second argument being passed on()
method acts filter original selector bind event handler to. explain example provided in plain english, telling browser listen clicks everywhere on page, , check if clicked happens <a>
element class of delete-mix
. if did happen click on a.delete-mix
, callback function run. if didn't, nothing happen.
this not best solution. adding global click handler document
can cause problems. better solution replace document
more specific, such container element wrapping dynamic boxes adding. without more code i'm not entirely sure selector should be.
for more information, should read jquery documentation on()
method.
hope helps.
Comments
Post a Comment