E prevent default not working - javascript

This is the code I am working with: http://jsfiddle.net/qKyNL/12/
$('a').click(function(){
event.preventDefault();
var number = $(this).attr('href');
alert(number);
// AJAX
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
}
});
});
I am trying to create a degradable pagination, using Jquery but the problem is that the "e prevent default" doesn't seem to trigger and instead it still follows the link. Could anyone please show me how I can have this link degradable so if Jquery is disabled it still works.

You're not passing in the event object. Try this:
$('a').click(function(event){ // <-- notice 'event' passed to handler
event.preventDefault();

Should be
$('a').click(function(event){
on first line. Note that event is passed as an argument to anonymous function.

No event passing in callback.
Try
$('a').click(function(event){
------------------------------^
event.preventDefault();
}

As the other answers have said you need to pass the event variable to the callback
$('a').click(function(event) {
event.preventDefault();
});
You also need to wrap all of your code in to the ready function jQuery so that the event listeners are assigned only when jQuery is ready to handle them.
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
// the rest of your code
});
});

Related

auto close popup after second

I am using simple popup and I want to auto close popup after seconds. Please guide me how to do that
jQuery(document).ready(function($) {
$(".movenext").on("click", function(e) {
e.preventDefault();
$(this).simplePopup({
type: "html",
htmlSelector: "#popupuser"},
setTimeout(function(){
$(this).simplePopup().close();
}, 3000)
);
});
});
Try this,, you are loosing the this scope inside setTimeout callback, see if that works
jQuery(document).ready(function($) {
$(".movenext").on("click", function(e) {
e.preventDefault();
var self = this;
$(this).simplePopup({
type: "html",
htmlSelector: "#popupuser"
});
setTimeout(function() {
$('.simple-popup-content .close').click();
}, 3000);
});
});
EDIT:
I've updated your fiddle, see it here: https://jsfiddle.net/8vx0185d/1/
The callback given to setTimeout has no "this" value. Use a variable to store $(this) and use it in your setTimeout callback
jQuery(document).ready(function($) {
$(".movenext").on("click", function(e) {
e.preventDefault();
var element = $(this);
element.simplePopup({
type: "html",
htmlSelector: "#popupuser"
});
setTimeout(function(){
element.simplePopup().close();
}, 3000);
});
});

Jquery applying class and removing class

The code which changes the active class to the currently clicked pagination class. Removing it works but adding the new class doesn't work.
http://jsfiddle.net/spadez/qKyNL/35/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
$('#pagination li.active').removeClass("active");
$(this).parent().addClass("active");
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
Can anyone please tell me where I am going wrong?
The problem is that this in the success callback isn't your element.
You may do this :
$('a').click(function(event){
var element = this; // <= save the clicked element in a variable
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
...
success: function (data, textStatus) {
...
$('#pagination li.active').removeClass("active");
$(element).parent().addClass("active"); // <= use it
},
...
});
});
This this in ajax callback isn't what you expect it to be. Add this to your ajax parameters:
context: this,
No need to build custom object saving system and making code more messy, as jQuery already has this functionality.
Edit: In this case it should look like:
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
context: this,
url: "/ajax_json_echo/",
...

Code is not executed after the jquery ajax complete event

i have tried to execute some code inside the ajax complete event but it doesn't work on the page load event , but it works perfectly in the onchange link event
$(document).ready(function() {
$.ajax({
beforeSend: function() {
// Handle the beforeSend event
},
complete: function() {
// Handle the complete event
$("#customfields_1 :input").filter(function() {
return $.trim(this.value).length === 0;
}).closest("td").hide();
}
// ......
});
});
$(document).ready(function() {
$.ajax({
url: 'http://foo.bar.com/some.json', // this is the important part
beforeSend: function() {
// Handle the beforeSend event
},
complete: function() {
// Handle the complete event
$("#customfields_1 :input").filter(function() {
return $.trim(this.value).length === 0;
}).closest("td").hide();
}
// ......
});
});

event.preventDefault not working. Ajax call causing this?

I'm trying to use scrolltop method and event.preventDefault is not working properly.
What I'm experiencing is that the page scrolls UP first then scrolls down.
It seems that The onclick causes the page to resubmit or something... (ajax post??)
I have following code
button (trigger)
<a id="nextset" class='nextbtn' >Next Step</a>
event
jQuery('#nextset').click(function (event) {
event.preventDefault();
movenext('set');
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 2000);
});
functions
function getfav(obj) {
var myParams = "{ 'proattr':'" + obj + "'}";
jQuery.ajax({
type: "POST",
url: "project.aspx/getproject",
data: myParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () { jQuery('#wait').show(); },
complete: function () { jQuery('#wait').hide(); },
success: function (msg) {
GetProjectPic(msg.d, obj); //creates DOM and insert in div
Initbtns();// dynamic btns initialization
}
});
}
function movenext(obj) {
//other codes to hide/show DOM
getfav(nextobj);
}
If I add return faulse; in onclick event, the button doesn't work.
Any idea what's causing the scrolling to the top?
UPDATE:
It was caused by code block inside movenext function.
jQuery('[id^="favdiv"]').empty();
nothing to do with event.preventDefault.
The strange thing is that the screen scrolls much more than hidden div height ("favdiv") which causes up and down screen effect. I'm not sure how to prevent it...
UPDATE2
I searched jquery empty method and found this.
jquery "empty" changes the scrollbar
You can avoid the default behaviour by using the following snippet:
<a id="nextset" class="nextbtn" href="javascript:void(0);">Next Step</a>
Did you by any chance try putting "return false" at the end of your click event?
jQuery('#nextset').click(function (event) {
movenext('set');
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 2000);
event.preventDefault();
return false;
});
I end up writing something like this. still it goes up a bit but at least page doesn't jump
jQuery('#favdiv' + obj).fadeOut('fast', function () {
jQuery('#favdiv' + obj).remove();
});
setTimeout(function () {
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 1500);
}, 500);

jquery ajaxStart/ajaxStop not working

i have very simple code that i making partial postback by jquery and i use ajaxStart/ajaxStop for doing some work. but it is not working. i just could not understand why it is not working.
here is my code
$("#imgHolder").ajaxStart(function () {
$('div#content').block({
message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>',
css: { border: '1px solid #a00' }
});
$('#imgHolder').empty();
$("#btnPrint").hide();
});
$("#imgHolder").ajaxStop(function () {
$("#btnPrint").show();
$('div#content').unblock();
});
$(document).ready(function () {
$.ajax({
type: "POST",
url: "UPSLabelFormUK.aspx/ProcessInfo",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d[0].Message == "SUCCESS") {
//alert(data.d[0].TrackNumber);
///alert(data.d[0].LabelImagePath);
var _images = [data.d[0].LabelImagePath];
$.each(_images, function (e) {
$(new Image()).load(function () {
$('#imgHolder').html("<img src='" + data.d[0].LabelImagePath + "' width='310' height='402' border=0/>");
}).attr('src', this);
});
}
} ,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
i just dont not understand why my above ajaxstart/ajaxstop did not work. please help me to understand why was wrong in my code.
but my ajaxstart/ajaxstop started working when i change the code a bit like
$(document).ajaxStart(function () {
$('div#content').block({
message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>',
css: { border: '1px solid #a00' }
});
$('#imgHolder').empty();
$("#btnPrint").hide();
});
$(document).ajaxStop(function () {
$("#btnPrint").show();
$('div#content').unblock();
});
the only change is $(document).ajaxStop(function () { instaed of
$("#imgHolder").ajaxStart(function () {
so please explain why my above ajaxStart/ajaxStop code did not work. thanks
Given the fact that ajaxStart is only called if there are no other
ajax requests in progress, it makes is useless if you want to use it
as an AJAX loader indicator.
have u tried with ( tell me is it working or not)
jQuery(document).ajaxStart(function(){
alert("it begins");
})
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
from jquery api web page of "ajaxStop". You can check it here.
Try this:
$("#loading").bind({
ajaxStart: function() { $(this).show(); },
ajaxStop: function() { $(this).hide(); }
});
Essentially binding your loadingAnimationElement to the globally fired ajaxStart and ajaxStop events. Only shows up when you intend it to.
When jQuery is not performing any Ajax requests and a new request is initiated, it fires an ajaxStart event. If other requests begin before this first one ends, those new requests do not cause a new ajaxStart event. The ajaxStop event is triggered when the last pending Ajax request is completed and jQuery is no longer performing any network activity.
This combination works fine. Thanks to user #brroshan
JS of Master page
<script language="JavaScript" type="text/javascript">
$(document).ajaxStart(function () {
$("#loading").show();
});
$(function () {
// Some other code
// The end of this code block
$("#loading").hide();
$("#loading").bind({
ajaxStart: function () { $(this).show(); },
ajaxStop: function () { $(this).hide(); }
});
});
</script>
html of Master page
<div id="loading" class="display: none;">
<h2>Loading...</h2>
</div>
Try this sample code:-
var $loading = $('#div_Loader').hide();
$(document).ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
setTimeout(function () {
$loading.hide();
}, 1000);
});

Categories

Resources