Reputation: 33755
Basically, I have a div that I want to apply a highlight
and bounce
effect to.
If I do just one, it works fine. But combining them seems to be much more tricky than I expected.
I tried to do simply this:
$('.highlight_on_success').bind("ajax:success", function(){$(this).closest('div.social-comment').effect('highlight').effect('bounce');});
But that didn't work, then I did some reading and I tried using dequeue()
like so:
$('.highlight_on_success').bind("ajax:success", function(){$(this).closest('div.social-comment').effect('highlight').dequeue().effect('bounce');});
But that too didn't work.
I eventually stumbled across this answer on SO about something similar, but that feels WAAAAAYYY too heavy.
Is there a simpler, more native, less hacky, way to achieve what I am trying to do?
Upvotes: 0
Views: 71
Reputation: 40038
The AJAX success function can be used like this:
var xhr = $.ajax({
type: 'post',
url: 'ajax_processor_file.php',
data: {varName : varValue}
});
xhr.done(function(){
$('.highlight_on_success')
.closest('div.social-comment')
.addClass('highlightMyDiv')
.effect( "bounce", {times:3}, 300, function(){
$(this).removeClass('highlightMyDiv');
});
});
or just:
var xhr = $.ajax({
type: 'post',
url: 'ajax_processor_file.php',
data: {varName : varValue}
})
.done(function(){
$('.highlight_on_success')
.closest('div.social-comment')
.addClass('highlightMyDiv')
.effect( "bounce", {times:3}, 300, function(){
$(this).removeClass('highlightMyDiv');
});
});
$('button').click(function(){
$('.social-comment')
.addClass('highlightMyDiv')
.effect( "bounce", {times:3}, 300, function(){
$(this).removeClass('highlightMyDiv');
});
});
.highlightMyDiv{background:wheat;border:1px solid orange;color:brown;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="social-comment">
The social comment div
</div>
<button>Simulate AJAX Callback</button>
Notes:
(1) The .effect()
method is part of jQueryUI, so that library must be referenced/included.
(2) You can add the CSS using addClass
and chain jQuery methods as above.
(3) Above code is not hijacking the AJAX function; it is the best practices methodology for writing an ajax routine, as per the jQuery API docs.
(4) In the previous person's answer, perhaps the DIV is not bouncing because the jQueryUI library is not included? Note that .effect()
is not part of jQuery, it is part of jQueryUI - but you can also load just the effects plugin individually.
(5) Note that .bind()
has been deprecated as of jQuery 1.7 in favor of .on()
(virtually the same syntax).
Upvotes: 0
Reputation: 854
You can provide a function callback to effect()
:
$('.highlight_on_success').bind("ajax:success", function () {
var obj = $(this).closest('div.social-comment');
obj.closest('div.social-comment').effect('highlight', function() {
obj.effect('bounce');
});
});
Upvotes: 2