Reputation: 15
So, i have such problem: first time, then the <a>
get clicked e.preventDefault()
isn't working and I jump to the top of the page, but on the second time it works. What is the problem?
$('#more a').live('click', function(e) {
var last = $('p.post').last().data('id');
console.log('start');
if (last != '1') {
$.ajax({
type: "POST",
url: "http://live.iappleworld.ru/ajax_more_mobile.php",
data: "last=" + last,
beforeSend: function() {
$('#more a').text('').prepend('<img src="http://live.iappleworld.ru/ajax-loader.gif" alt="loading"/> Loading...');
},
success: function(html) {
$("#more").remove();
$(html).hide().appendTo('ul.pageitem').slideDown(600);
}
});
}
e.preventDefault();
});
Before and after i have another script.
Upvotes: 0
Views: 2468
Reputation: 1
Sounds like none of the javascript file is being loaded on the first visit to the page. Then you click the link and it is followed "normally", this refreshes the page and loads your javascript which then intercepts your click events from then on, as you expected.
Is the area with the (un)affected links on it loaded via ajax?
Upvotes: 0
Reputation: 87073
$('#more').on('click','a', function(e) {
e.preventDefault(); // at the beginning stop page reload
// your code
});
.on()
Syntax of .on()
for delegate event handling:
$(container).on(eventName, target, handlerFunction)
Where container
is any Static element
within which the target
element belong and of course container should belong to DOM at page load i.e it should not dynamic.
Read more aboue .on()
Try to avoid .live()
if you have choice to use jQuery >= 1.7
and bind delegate event with .on()
.
You've wrote
$('#more').live('click','a',function(e) {...});
but it should be
$('#more').on('click','a',function(e) {...});
a
tag href
to<a href="javascript:void(0)"></a>
and remove e.preventDefault()
.
Upvotes: 4
Reputation: 2150
Instead of using .live method, use delegate
. I'm not sure about your html structure however i think this might work.
$('#more').delegate('a','click', function(e) {
var last = $('p.post').last().data('id');
console.log('start');
if (last != '1') {
$.ajax({
type: "POST",
url: "http://live.iappleworld.ru/ajax_more_mobile.php",
data: "last=" + last,
beforeSend: function() {
$('#more a').text('').prepend('<img src="http://live.iappleworld.ru/ajax-loader.gif" alt="loading"/> Loading...');
},
success: function(html) {
$("#more").remove();
$(html).hide().appendTo('ul.pageitem').slideDown(600);
}
});
}
e.preventDefault();
});
Upvotes: 0