To avoid the default click action, modify your click handler as follows:
.on('click', '.item', function(e) {
var ...
e.preventDefault();
$.ajax({
...
)}
...
})
Adding e
to the click handler function means that the event details are available within the function - on the e
object you run the preventDefault()
method which prevents default actions from occuring - for instance, a hyperlink will no longer navigate to its target.
The event occurs in generally the following manner, though this is don't an in-depth summation:
A click event occurs on the a
element.
The click event starts a search for an event handler. Should one not be found on the element that caused then the event will 'bubble' up the DOM tree, one level at a time until it either reaches the root DOM element and cannot go further, or a click handler is found.
At any point, should a click handler be found then the code in the click handler is executed. If the click handler sets preventDefault()
on the event object, or returns false
then no further action is taken.
If the click handler neither returns false
nor sets preventDefault()
then the original browser default action will be executed in addition to your own event handler.
Your code in full with modifications:
<script>
(function($) {
$(document).ready(function() {
var container = $('.masonry'), masonry;
//masonry = new Masonry(container[0]);
container.masonry('stamp', container.find('.stamp'));
container.unbind('click').on('click', '.item', function(e) {
var $this = $(this),
this_link = $this.find('a'),
$this_link = $(this_link),
this_href = $this_link.attr('href'),
video_id = $this.attr('data-video-id'),
gigante = $this.hasClass('gigante'),
selector = 'div#panel-area.video_grid div.masonry div.item.' + video_id;
e.preventDefault();
$.ajax({
type: "GET",
async: false,
url: this_href,
timeout: 5000,
data: {'g': gigante},
dataType: 'html',
success : function(data) {
$(selector).html(data);
container.find('.item').removeClass('gigante');
$(this).toggleClass('gigante', !gigante);
container.masonry();
console.log('Selector: ' + selector + '\nSuccess');
}
})
.done(function(msg){
console.log('Done: ' + msg);
})
.fail(function(jqXHR, textStatus){
console.log('Failed: ' + textStatus);
});
});
});
})(jQuery);
</script>