This question already has answers here:
Making jquery plugins work after an Ajax call
(3 answers)
Chosen not working on elements from AJAX call
(2 answers)
Closed 1 year ago.
So I have this Jquery functions that I've created using delegations and call each functions in the documeny.ready.
$(document).ready(function () {
getContent();
getQuoteButtton();
popupModal();
plugins();
});
function getQuoteButtton() {
// button quote
$("body").on("click", ".btn-quote", function (e) {
var $this = $(this);
$this.toggleClass('quote-selected');
if ($this.hasClass('quote-selected')) {
$this.text('Selected');
} else {
$this.text('Select This Quote');
}
});
}
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php');
});
}
function popupModal() {
/*Toggle popup-modal class */
$("body").on("click", ".popup-modal-toggle", function (e) {
$('.popup-modal').fadeIn().show();
});
//close popup button
$("body").on("click", ".popup-close", function (e) {
$('.popup-modal').fadeOut().hide(300);
});
}
function plugins() {
// phone number plugin initialized singapore and malaysia only
$("#phone-num").intlTelInput({
initialCountry: "SG",
onlyCountries: ['SG', 'MY'],
utilsScript: './resources/vendors/intl-tel-input-master/js/utils.js'
});
// Select tags with search bar
$(".chzn-select").chosen();
}
The other functions is working fine but when I call the plugins function it doesn't seem to load after using the getContent.
The getContent function is where I handle my ajax call to load each pages in the section using the div element #get_content
I don't understand why my plugins function is not working. Does anybody know why? Do I have to call each functions in plugins to use delegations also? if so, what's the process? Thanks.
EDIT - Correct Answer
I have find out the solution, in the getContent function, I also added the plugins() function inside to fetch it after ajax. I don't know why this question was closed even though I have a different approach in coding.
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php', function (response, status, xhr) {
// include the plugins function after the content loads -> if no initialization function won't load
plugins();
});;
});
}
Related
I have an external html code that I am loading it dynamically using load function of jQuery:
_this.load = function () {
_this.view.container.load("html/index.html", function () {
_this.view.loadAnimation();
});
}
this.loadAnimation = function() {
_this.heading = _this.container.find(".heading");
_this.subheading = _this.container.find(".subheading");
_this.reserve = _this.container.find(".reserve");
_this.heading.addClass('hanimate');
_this.subheading.addClass('sanimate');
_this.reserve.addClass('ranimate');
}
Now the problem is that the function _this.view.loadAnimation(); is not running in the callback function of load. It works only if I add delay to the callback as the following:
_this.load = function () {
_this.view.container.load("html/index.html", function () {
$(window).delay(100).queue(function() {
_this.view.loadAnimation();
});
});
}
I understand that all elements of inside "html/index.html" must be loaded before executing the loadAnimation();
The question is: isn't there a way or event that I can trigger when all elements of this "html/index.html" are loaded? into main div? how can I modify my code for this purpose?
Update: As requested, I have a an example in Codepen:
https://codepen.io/khaled85/pen/eyqQGz
Best,
This question already has answers here:
JavaScript - Owner of "this"
(6 answers)
Closed 6 years ago.
I've got span inside an LI with a class of removeFile, when clicked, it should remove a file using jQuery $.get and then upon successful deletion, it should fadeout the containing LI. I can't figure out why this is not working, I can get it to alert(data) but not assign to a variable or execute the fadeOut() command.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$(this).parent().fadeOut();
}
});
}
});
<li class="file">
<span class="file" data-file-url="http://demo.com/filemanager/files/test.txt" title="test.txt">test.txt</span>
<span class="removeFile" data-file-url="/files/test.txt"></span>
</li>
Inside ajax callback function this refers to jqXHR object, so you need to define it outside the ajax call as variable or set it the context option.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var $this = $(this);
var fileUrl = $this.data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$this.parent().fadeOut();
}
});
}
});
this in get() not referencing .removeFile. this refers to xhr object in the callback of get().
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var li = $(this).parent(); //added this line
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')) {
$.get('process.php', { 'remove-file': fileUrl }, function (data) {
if (data == 'true') {
li.fadeOut(); //changed this line
}
});
}
});
I have a web application with a medium amount of ajax requests.
I load all jquery and jquery widgets on head then i load my base.js before close body tag.
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
}
SCRIPT BLOCK TO LOAD BASE SCRIPTS ON EVERY AJAX REQUEST
$(document).ajaxComplete(baseScripts);
The problem is after every ajax request the base scripts its called again and them opening dialog multiple times and attaching select2 multiples times too.
How i can detect if widget is already attached into element or class?
Execute scripts on every ajax request (like i did) its a bad pratice?
It doesn't make sense that you will want to re-bind the click event and select2 on ajaxComplete. They should be a one-time binding, in which case, you can just do:
$(document).ready(function(){
baseScripts();
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
});
I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE
There are some similar questions, but they all seem like regarding native jQuery callback functions.
So I have this code which (live) creates a div containting some form elements.
Values of these elements should be retrieved inside a callback function when (before) the div is removed.
function popup(callback) {
// ...
// before removing the div
callback.call();
// remove div
}
Unexpectedly, the callback function is being fired multiple times (increasingly) after the first time popup is executed.
I have simplified the code, and here is the fiddle.
I hope this is what you need.
function popup(callback) {
$("body").append('<div><span id="test">test</span> close</div>');
$(document).on("click", "#close", function() {
callback.call();
//
//callback = function() {};
$(document).off("click", "#close");
$("div").remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Basically, you need to remove event handler by invoking off() method.
Try dynamically generating the elements instead of using a string. This will allow you to bind events easier.
function popup(callback)
{ var $elem = $("<div></div>");
$elem.append($("<span></span>").html("test"));
$elem.append(" ");
$elem.append($("<a></a>").html("close").attr("href", "#"));
$("body").append($elem);
$elem.find("a").click(function() {
callback.call();
$elem.remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Example: http://jsfiddle.net/4se7M/2/
I don't know the exact scenario, but why do you want to bind and unbind the event each time you show the popup?
You can bind only once, like this, can't you?
$(document).on("click", "#close", function() {
alert('$("#test").length = ' + $("#test").length);
$("div").remove();
});
function popup() {
$("body").append('<div><span id="test">test</span> close</div>');
};
$(document).on("click", "#open", function() {
popup();
});