I have the following script in between the head tags on my page:
$.ajax({
type: "POST",
url: "my script that gets what I need",
context: document.body,
success: function(data){
//data is now the value that PHP echoed
phpsaid = data.split('|');
var size_ind = phpsaid.length/6;
var size_per = 6;
for (var i_one =0; i_one<size_ind; i_one++){
for(var i_two =0; i_two<1; i_two++){
if(i_one == 0 ){
var i_get = 0
}
else{
var i_get = i_one * 6;
}
$("#big_container").append("<div class ='neato'><div class ='c1'>"+phpsaid[i_get]+"</div><div class ='c2'>"+phpsaid[i_get+1]+"</div><div class ='c3'>"+phpsaid[i_get+2]+"</div><div class ='c4'>"+phpsaid[i_get+3]+"</div><div class ='c5'>"+phpsaid[i_get+4]+"</div></div>")
}
}
}
});
Then in the main body I have:
<div id ="big_container">
</div>
The ajax script above is generating the divs to go inside big_container. The client has specified that it be done strictly in that way (meaning generate all divs with ajax on the fly), so conceptual arguments of different ways to tackle it unfortunately won't help much here.
Here is my problem:
I also want to apply the following plugin to all elements of big_container. This of course works perfectly when I hard code the div elements into the page, but I cannot get it to work on the ajax generated divs within #big_container.
$(function(){
$('#big_container').bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
});
How do I get the plugin function to apply to the ajax generated div's once they have in fact been generated?
Insert your initialization code after $("#big_container").append("...");
It will look like
$("#big_container").append("<div class ='neato'>..and so on..");
}
} // the end of the 'for' loops
$("#big_container").bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
If you call ajax again on the page and add a new content to the existing one then it is better to write the call of the bxSlider as
$("#big_container .neato:last").bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
just after .append part
This is a common problem people face that elements generated by ajax (dynamically inserted in to dom) doesn't take action or notified by any of the listener or any plugin inside ready because they are not registered in the ready event. To solve this kind of problem I use a different approach like the following
$(document).ready(function(){
myReadyFunction();
});
function myReadyFunction()
{
$("#big_container .neato:last").bxSlider({...});
// All other codes that normally reside inside ready event.
}
After each ajax call, upon success (if required) simply call myReadyFunction(); and in your case you can place your $("#big_container").bxSlider({...}) inside the myReadyFunction(); and call the myReadyFunction(); after successful ajax call and initially call myReadyFunction(); inside ready event too.
Related
I am working on a normal bootstrap theme which contains js slider, popup, text-rotation, masonry boxes etc..
The theme contains all relevant js library and main.js
All of these will load new content via ajax on user specified actions.
Here is the js/ajax for text-rotation:
In the example below i have to call the "$('.text-rotation').owlCarousel" in order to make the text-rotation to work properly.
function getCon(type,id)
{
var postData = { id: id, type: type}
$.ajax({
url : 'getcontent.php',
type : 'post',
data : postData,
success : function( resp ) {
var cont = $('#cont', resp).html();
$('#conta').after(cont);
$('.text-rotation').owlCarousel({
loop: true,
dots: false,
nav: false,
margin: 10,
items: 1,
autoplay: true,
autoplayHoverPause: false,
autoplayTimeout: 3800,
animateOut: 'zoomOut',
animateIn: 'zoomIn'
});
}
});
}
When not calling "$('.text-rotation').owlCarousel" it simply displays the text in list format.
In order to make the all the ajax load content work properly on all section i.e the slider, popup, etc.. i'll have to find the relevant theme functions and code them all on the respective ajax functions.
Is there any predefined js code which i may call on ajaxComplete so tha all ajax content works normal as it works on page load ??
I tried to call the main.js from "getScript" function inside the ajax success but not working..
The short answer is: no.
jQuery code acts on the DOM that exists when the code is run; if you add to the DOM later on there isn't any general-purpose way for jQuery code to go back and act on the new elements as though they had been there in the first place.
Your options are
rewrite your code to not depend on event bindings / manipulation of the AJAX-based content -- instead use delegated event bindings on elements that are always present
defer your main code init until after all AJAX calls have completed, so the DOM is already in place when you add your bindings
Write specific code to add necessary event bindings / modify newly added DOM chunks individually, as they're loaded
[!Newbie alert!] I'm using a ecommerce platform that doesn't allow me to edit the source code. I can only add new codes (html, js or css) to try to do the modifications I want. And what I want to do is to find a way to disable the script of a newsletter popup on only one specific page. The only way I thought of doing it is adding an extra JS script limiting the action of the previous script that I am not allowed to edit. Is it possible to do?
The original script for de Newsletter Popup is this:
<script type="text/javascript">
$(function() {
iniciarModalNews();
});
function iniciarModalNews() {
if (!$.cookie('showModalNews')) {
showModalNews();
};
}
function showModalNews() {
$.fancybox.open({
type: 'html',
minWidth: 270,
maxWidth: 350,
content: $('#modalNewsletter'),
beforeClose: function() {
$.cookie('showModalNews', 'hide', {
expires: 1,
path: '/'
});
}
});
}
</script>
It runs on all pages of the website and I want to exclude just one page. Is there a way to do this?
Thanks
Full Disclosure: This suggestion would not be considered a best practice but if its a one-off scenario where you don't have access to the source code it'll work.
If you only need to disable this on one page and have access to insert a block of script below the declaration of showModalNews() { ... } you can override the showModalNews() function by writing a new function with the same name. The method that calls the showModalNews method is inside an closure via IIFE (https://developer.mozilla.org/en-US/docs/Glossary/IIFE) but the method showModalNews() is NOT wrapped in a closure which would give you access to override it.
Example of the overridden method
function showModalNews() { ; }
I can't find a solution for this plugin since I cannot find any working demo or documentation for external content via Ajax.
Basically I have a simple div with a mouse hover JS function:
<div onmouseover="myFunct(this,'.$comment['id'].');" >Hover Me</div>
And this is my JS function:
function myFunct(element, id){
$(element).tooltipster({
contentCloning: true,
interactive:true,
maxWidth:250,
contentAsHTML:true,
content: 'Loading...',
// 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
functionBefore: function(instance, helper) {
var $origin = $(helper.origin);
// we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
if ($origin.data('loaded') !== true) {
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+id+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
// to remember that the data has been loaded
$origin.html('loaded', true);
}
});
}
}
});
}
Why the tooltip is shown only at the 2nd mouse hover?
Here is a similar Eg. JSFiddle
UPDATE
Thanks to the support this has solved my issue:
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, and I don't know why (I tried to insert it on Ajax page, no way)
I'd recommend a few things: first, separate your JS from your HTML (this is considered best practice), second, initialize Tooltipster on page load, and last, remove the wrapper function. Once the tooltip is initialized your code will trigger by default on hover.
Separate JS from HTML
<div class="hover-me tool-tip" data-commentId="12345">Hover Me</div>
Initalize Tooltipster on Document Ready
$(document).ready(function() {
$('.tooltip').tooltipster();
});
Trigger Tooltipster with Hover
$('.hover-me').tooltipster({
// all of your code from above
functionBefore: function(){
var commentId = $(this).attr('data-commentId');
}
});
Note:
The default trigger for Tooltipster is hover (as seen in the documentation), however, you could explicitly set it by passing in trigger: hover, which would make your code slightly more readable and as such maintainable.
Tooltipster Support Recommendation (as seen in the comments)
I add this because it reinforces my solution above and adds context for future devs...that, and it might be overlooked in the comments section.
You initialize your tooltip when the mouseover event has already been fired, so Tooltipster cannot "hear" this first event and open the tooltip. You'd better initialize your tooltips at page load and put your comment id in a data-id attribute that you'll retrieve in functionBefore when you prepare your ajax call.
I need to bind a function to initialize a js plugin after {Permalink} is clicked so Tumblr IPA "redirects" the browser to a new page, with the post details.
How can I do so? There's not so much documentation on how {Permalink} really works, whether it's ajax or whether it has some callback function (which I would appreciate).
Of course this would try to initialize before the "new" page is loaded. I think it's ajax though.
$("#{Permalink}").click(function() {
$('.jqzoom').jqzoom({
zoomType: 'standard',
lens:true,
preloadImages: false,
alwaysOn:false
});
});
{Permalink} renders a string that is the URL to the post: http://sample.tumblr.com/post/123
For reference, Tumblr theme operators don't have anything to do with javascript. They render mainly strings.
You need to bind the actual element that is clicked:
HTML
...
jQuery
$(".permalink").click(function() {
...
});
Reference: http://www.tumblr.com/docs/en/custom_themes#posts
is it possible using fancybox to post a var to the iframe when opens?
I currently have:
function fancyBoxLoad(element) {
var elementToEdit = $("#" + $(element).attr("class"));
var content = encodeURIComponent($(elementToEdit).outerHTML());
$.fancybox(
{ 'href': 'loadEditor.php' },
{
frameWidth: 750,
frameHeight: 430,
overlayShow: true,
ajax: {
type: "POST",
data: 'content=' + content
},
type: 'iframe'
}
);
}
It does seem that if I take away type: 'iframe' it will post data but it doesn't appear to be in the iframe and if I take away ajax: { type: "POST", data: 'content=' + content } instead it will open in an iframe but not post the data (the example above does the same)
So my question being can it be done?
If you're simply trying to put content in a iframe, why don't you use fancybox to create the iframe, and once you know it's been created, then access it via the reference that fancybox returns to you and set your content that way. I'm not sure you want to send the content to the server and back. Just wait for the iframe to load, then on ready, query an element within it and set the content.
Looking at the source for Fancybox v1.3.1 they are in fact mutually exclusive. If you don't feel comfortable diving into the source code and editing the plugin, you might try using GET variables in your HREF as a work around. It should effectively work like a post as it is an AJAX call, just make sure the backend can receive the GET variables.