Is it possible to debounce the click of a link? If a user clicks too many times too fast on a pjax link it'll break the load of new content.
$(document).on('click', 'a[data-pjax]', loadNewContent);
var $target = $('main.content section.context'),
$fake = $('main.fake'),
$fakeContext = $('main.fake section.context');
function loadNewContent() {
event.preventDefault();
var $this = $(this),
url = $this.attr('href');
$fake.addClass('is--loading');
$.pjax({
url: url,
fragment: 'body',
container: $fakeContext
});
$fake.one(transitionEnd, function() {
$target.html($fake.find('section.context').html());
$fake.removeClass('is--loading');
$fake.off(transitionEnd);
});
}
Any thoughts? I tried this, but it stopped the loadNewContent from firing. (https://github.com/cowboy/jquery-throttle-debounce)
$(document).on('click', 'a[data-pjax]', $.debounce(1000, true, function() {
loadNewContent();
}));
Something like this would work :
var callWaiting = false;
callAjax() {
if(!callWaiting) {
callWaiting = true;
makeHttpCall(url, data, function(response) {callWaiting = false;});
callWaiting = false;
}
}
Related
I am attempting to perform some action on the foucsin of the textbox. However, for some reason the event never fires.
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
$(window.open(urlstring, 'Contacts', 'width=750, height=400')).load(function (e) {
// Here "this" will be the pop up window.
$(this.document).find('#txtAutocompleteContact').on({
'focusin': function (event) {
alert('You are inside the Contact text box of the Contacts Popup');
}
});
});
});
});
When doing it that way, you generally have to find the body or use contents() to access the contents, as in
$(this.document).contents().find('#txtAutocompleteContact')
but in this case using a little plain javascript seems more appropriate :
$(".ddlAddListinTo li").on('click', function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
var wind = window.open(urlstring, 'Contacts', 'width=750, height=400');
wind.onload = function() {
var elem = this.document.getElementById('txtAutocompleteContact');
$(elem).on('focus', function() {
alert('You are inside the Contact text box of the Contacts Popup');
});
}
});
});
I have this piece of code , that does not work , if I link JQUERY above 1.8.0
Just for curiosity, why its happening?
it takes values from select boxes, passing to pagination.php file and in the meantime showing loading image
// Pagination
$(document).ready(function () {
function loading_show() {
$('#loading').html("<img src='img/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading').fadeOut('fast');
}
function loadData(page) {
var house_id = $("#pbthouse option:selected").val();
var sale_id = $("#pbtsale option:selected").val();
var year_id = $("#pbtsale option:selected").val();
var ipp = $("#res option:selected").val();
loading_show();
$.ajax({
type: "POST",
url: "pagination.php",
//data: "page="+page,
data: {
page: page,
house_id: house_id,
year_id: year_id,
sale_id: sale_id,
ipp: ipp
},
success: function (msg) {
$("#container1").ajaxComplete(function
(event, request,settings)
{
loading_hide();
$("#container1").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container1 .pagination li.active').live('click', function () {
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click', function () {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if (page != 0 && page <= no_of_pages) {
loadData(page);
} else {
alert('Enter a PAGE between 1 and ' + no_of_pages);
$('.goto').val("").focus();
return false;
}
});
$('#container1 .pagination li.active').live('click', function () {
var page = $(this).attr('p');
loadData(page);
});
$("#pbthouses").change(function () {
var page = '1';
loadData(page);
});
$("#res").change(function () {
var page = '1';
loadData(page);
});
$('#pbtsale, #pbtyear').change(function () {
var sale_id = $("#pbtsale option:selected").val();
var sale_id = $("#pbtyear option:selected").val();
var page = '1';
if (sale_id != '') {
$.ajax({
type: "POST",
url: "get_pbtsales.php",
data: {
year_id: year_id,
sale_id: sale_id
},
success: function (option) {
$("#pbhouses").html(option);
loadData(page);
}
});
} else {
$("#pbhouses").html("<option value=''
>-- No category selected --</option>");
}
return false;
});
});
Support for .live() has been deprecated since version 1.7 and removed since version 1.9. You should switch to the dynamic form of .on() which would change from this:
$('#go_btn').live('click', function () {
to this:
$(document).on('click', '#go_btn', function () {
Ideally, instead of $(document), you would pick a closer parent of #go_btn that is static (e.g. not dynamically created) as this is more efficient than using $(document), particularly if you have a number of delegated event handlers like this.
Some references for delegated event handling with .on():
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Should all jquery events be bound to $(document)?
Does jQuery.on() work for elements that are added after the event handler is created?
In my application, I have a piece of code that "catches" all the clicks on an anchor, and loads it into my page:
$("a").live("click", function () {
var src = $(this).attr("href");
if ($(this).attr("target") === "_blank")
return true;
$("#myPage").load(src + " #myPage");
return false;
});
Now this works on all anchor tags. How can I make all my POST requests (sending forms data) behave like that?
Edit: As Kevin said, I tried using .post, but it doesn't work for me, what did I do wrong? Here's the code:
$("form").post("submit", function () {
var src = $(this).attr("action");
$("#myPage").load(src + " #myPage");
return false;
});
Use the form submit event to handle form POST case
$(document).on('submit', 'form', function(){
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: 'POST',
data: $this.serialize()
}).done(function(responseText){
$("#myPage").html(responseText)
});
return false;
})
Since you are using jquery 1.9, you may have to rewrite the a handler as
$(document).on("click", 'a', function () {
var src = $(this).attr("href");
if ($(this).attr("target") === "_blank")
return true;
$("#myPage").load(src + " #myPage");
return false;
});
I'm trying to add some functionality to be able to edit comments inline. So far it's pretty close, but I'm experiencing issues trying to trigger a second event. It works the first time, but after that, fails.
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').append('saved');
clicked = false;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});
jsfiddle demo here
Hiya demo for your working solution: http://jsfiddle.net/8P6uz/
clicked=true was the issue :)) I have rectified another small thing. i.e. $('#output') is set to empty before appending another saved hence text **saved** will only appear once.
small note: If I may suggest use Id of the button or if there are many edit buttons try using this which you already i reckon; I will see if I can write this more cleaner but that will be sometime latter-ish but this should fix your issue. :) enjoy!
Jquery Code
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').text("");
$('#output').append('saved');
clicked = true;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});
I'm trying to build a Javascript listener for a small page that uses AJAX to load content based on the anchor in the URL. Looking online, I found and modified a script that uses setInterval() to do this and so far it works fine. However, I have other jQuery elements in the $(document).ready() for special effects for the menus and content. If I use setInterval() no other jQuery effects work. I finagled a way to get it work by including the jQuery effects in the loop for setInterval() like so:
$(document).ready(function() {
var pageScripts = function() {
pageEffects();
pageURL();
}
window.setInterval(pageScripts, 500);
});
var currentAnchor = null;
function pageEffects() {
// Popup Menus
$(".bannerMenu").hover(function() {
$(this).find("ul.bannerSubmenu").slideDown(300).show;
}, function() {
$(this).find("ul.bannerSubmenu").slideUp(400);
});
$(".panel").hover(function() {
$(this).find(".panelContent").fadeIn(200);
}, function() {
$(this).find(".panelContent").fadeOut(300);
});
// REL Links Control
$("a[rel='_blank']").click(function() {
this.target = "_blank";
});
$("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
$("#content").fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
}
}
This works fine for a while but after a few minutes of the page being loaded, it drags to a near stop in IE and Firefox. I checked the FF Error Console and it comes back with an error "Too many Recursions." Chrome seems to not care and the page continues to run more or less normally despite the amount of time it's been open.
It would seem to me that the pageEffects() call is causing the issue with the recursion, however, any attempts to move it out of the loop breaks them and they cease to work as soon as setInterval makes it first loop.
Any help on this would be greatly appreciated!
I am guessing that the pageEffects need added to the pageURL content.
At the very least this should be more efficient and prevent duplicate handlers
$(document).ready(function() {
pageEffects($('body'));
(function(){
pageURL();
window.setTimeout(arguments.callee, 500);
})();
});
var currentAnchor = null;
function pageEffects(parent) {
// Popup Menus
parent.find(".bannerMenu").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
subMenu: $(this).find("ul.bannerSubmenu"),
handlerIn: function() {
this.subMenu.slideDown(300).show();
},
handlerOut: function() {
this.subMenu.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
parent.find(".panel").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
content: panel.find(".panelContent"),
handlerIn: function() {
this.content.fadeIn(200).show();
},
handlerOut: function() {
this.content.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
// REL Links Control
parent.find("a[rel='_blank']").each(function() {
$(this).target = "_blank";
});
parent.find("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
var content = $("#content");
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
content.fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
pageEffects(content);
}
}
Thanks for the suggestions. I tried a few of them and they still did not lead to the desirable effects. After some cautious testing, I found out what was happening. With jQuery (and presumably Javascript as a whole), whenever an AJAX callback is made, the elements brought in through the callback are not binded to what was originally binded in the document, they must be rebinded. You can either do this by recalling all the jQuery events on a successful callback or by using the .live() event in jQuery's library. I opted for .live() and it works like a charm now and no more recursive errors :D.
$(document).ready(function() {
// Popup Menus
$(".bannerMenu").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find("ul.bannerSubmenu").slideDown(300);
} else {
$(this).find("ul.bannerSubmenu").slideUp(400);
}
});
// Rollover Content
$(".panel").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find(".panelContent").fadeIn(200);
} else {
$(this).find(".panelContent").fadeOut(300);
}
});
// HREF Events
$("a[rel='_blank']").live("click", function(event) {
var target = $(this).attr("href");
window.open(target, "_blank");
event.preventDefault();
});
$("a[rel='share']").live("click", function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
setInterval("checkAnchor()", 500);
});
var currentAnchor = null;
function checkAnchor() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn(200);
$("#content").fadeOut(200).html(data).fadeIn(200);
$("#load").fadeOut(200);
});
}
}
Anywho, the page works as intended even in IE (which I rarely check for compatibility). Hopefully, some other newb will learn from my mistakes :p.