Auto-refresh content inside a div? - javascript

I know this question has been asked several times. And I have read all the threads without coming to a solution. I use Wordpress, together with a plugin, this plugin lets me add events to it. I use the "shortcode"/[slug] on a Wordpress page. This displays the events I have added. If I add or remove an event I need to manually refresh the page to see this.
My goal is to be able to see the new events (and removed) without refreshing the whole page.
If I check the page with chrome together with the source I find that a div id="vs" is what contains all the events.
I have made an addition to the plugin where I've created a javascript.
jQuery(document).ready( function($) {
var auto_refresh = setInterval(
function() {
$.ajax({
url: "https://example.com",
success: function( data ) {
$("#vs").html( $(data).find('div').html());
}
})
}, 5000); // refreshing after every 5000 milliseconds
})
What happens is that it is refreshed automatically. But it displays a lot of elements, and it is a duplicate of the content that was already there. And everything is offset too.
I really don't know what to try?
And also, the page which this is displayed on is a slider, both displaying the same slug, but it only "works" on the first slider.
Any ideas?

So it's a little hard to answer without seeing what all the dom looks like but it sounds like you are not replacing the content but rather just adding to it over and over again. As a result, slowly the width content is getting smaller and smaller which is why you get the indenting affect. My guess is you're using .html when you want to be using .replaceWith
http://api.jquery.com/replacewith/
var auto_refresh = setInterval(
function() {
$.ajax({
url: "https://example.com",
success: function( data ) {
$("#vs").replaceWith( $(data).find('div').html());
}
})
}, 5000); // refreshing after every 5000 milliseconds
If this doesn't work I think we need to see what your dom looks like.

Related

How to print an iFrame with stylesheet?

I've created this code to print data from an iFrame
function (data) {
var frame = $("<iframe>", {
name: "iFrame",
class: "printFrame"
});
frame.appendTo("body");
var head = $("<head></head>");
_.each($("head link[rel=stylesheet]"), function (link) {
var csslink = $("<link/>", { rel: "stylesheet", href: $(link).prop("href") })
head.append(csslink);
;});
frame.contents().find("head")
.replaceWith(head);
frame.contents().find("body")
.append(this.html());
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}
This creates an iFrame, adds a head to where it sets all the css links that are needed for this website. Then it creates the body.
Trouble is, the styling won't get applied to the print, unless I break at line frame.contents().find("head").replaceWith(head), which means that something in that part is running asynchronously.
Question is, can I somehow get the code to wait for a short while before running that line, or is there perhaps another way to do this? Unfortunately I'm not all that familiar with iFrames, so I have no clue what it's trying to do there.
This turned out to be a real hassle. I've always been reluctant to using iframes, but since there are many resources saying that using an iframe for printing more stuff than what's on the screen, we figured we'd give it a try.
This was instead solved by putting the data inside a hidden div which then was shown before a window.print(). At the same time, all other elements on the page were given a "hidden-print" class which is a class we're already using to hide elements for prints.
This might not be as elegant for the user (The div will show briefly before the user exits the print dialogue), but it's a way more simpler code to use and manage.
I think you could / should move the last focus() and print() calls to a onload handler for the iframe, to get it to happen after styles are loaded and applied.
I've just run into the same issue and did the following:
setTimeout(() => {
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}, 500)
This appears to have sorted it for me. I hate using timeout and the length is guess work at best but as it's not system critical it's something I can run with for now.

WordPress Contact Form 7 Plugin behaves strange when it is part of AJAX-loaded content

I am currently trying to implement the WordPress Contact Form 7 Plugin into a WordPress-site I created. The theme uses jQuery to overwrite the default link behaviour and AJAX to load the requested page without actually reloading the whole page.
The problem is: The contact form works perfectly when the page where it is used on is loaded directly. However, if the page is loaded via AJAX, there are two strange behaviours: The Google reCAPTCHA widget is not showing up and after submit, instead of showing the div with the success-message, I am redirected to the themes "404" page. The mail gets sent successfully though. I use the plugin/contact-form in AJAX mode - so it makes an AJAX call itself to submit the data and handle the response without page refresh.
I am a bit overwhelmed where to start to solve this problem. Just for testing, I tried to hardcode all scripts from the direct pageload to the theme, so that they are also there when the contact-page is loaded via AJAX. Unfortunately, this didn't have any effect at all. I also tried to call the wpcf7InitForm() function of the plugin, as it was suggested in another question here - also with no success.
This is my ajaxload-script:
jQuery(document).ready(function($) {
// Targeting all internal links
$(document).on('click', 'a[href^="http://' + top.location.host.toString() + '"]:not([href*="wp-admin"])', function(event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax(url, {
beforeSend: function() {
if ($('#ajax-loader').length == 0) { $('body').append('<div id="ajax-loader"></div>'); }
$('#ajax-loader').fadeIn();
// Dimming static elements during loading
$('#mainbar').animate( { opacity: '0.5' } );
},
success: function(data) {
var data = $('<div />').html(data);
window.history.pushState('...', '...', url);
document.title = $(data).find('title').text();
$('#mainbar').html($(data).find('#mainbar > *'));
// Undoing design modifications to static elements
$('#mainbar').animate( { opacity: '1' }, 150 );
$('body').triggerHandler('reflow');
},
});
});
});
Help on this topic would be really appreciated and thanks in advance!
Couple ideas after reading through some stuff:
Might be a bug with the recaptcha - looks like the latest version specifically fixes recaptcha problems (not sure if they are yours though): http://contactform7.com/2015/11/23/contact-form-7-431/#more-16357
The div not showing up should be easy to debug by using absolute paths. In Wordpress, I usually use the bloginfo(); function. Try putting something like this in your form submit success callback to test path visibility between the AJAX and non-AJAX pages:
<?php
$pathCheck = bloginfo('template_directory');
echo $pathCheck;
?>
The problem with the div not showing up could also be how you are structuring the callback. From this question, it appears that the plugin has specific callback hooks you have to use that aren't in the documentation:
$(".your-form-class").on('wpcf7:mailsent', function(event){
// Show success div code would go in here
});
Great question btw. You used proper english and clearly explained your problem, pretty rare on S.O. Hope some of this gets you going.

Javascript won't load using jQuery Mobile with navigation-geolocation

I am having an issue with jQuery Mobile, javascript and get geolocaton.
I am currently using following to get the code to load, when I enter the page:
$(document).on('pageinit', function(){
If the user has set visibility to visible, a div with the ID visible is shown, this I use to call the geolocation the first time:
if ($('#visible').length) {
navigator.geolocation.getCurrentPosition(sucessHandler, errorHandler);
}
After this I call the geolocation every 20th second:
setInterval(function() {
if ($('#visible').length) {
navigator.geolocation.getCurrentPosition(sucessHandler);
}
}, 20000);
My issue is, if I leave the page for one of the subpages, and return to this page, these codes won't run again. I have tried the following to load the javascript, instead of pageinit:
$(document).on('pagebeforeshow', '#index', function(){
and
$(document).on('pageinit', '#index', function()
I tried loading it in the body of the index as well.
Any help would be greatly appreciated =)
Regards, Fred
Firstly, you may want to consider replacing navigator.geolocation.getCurrentPosition() with navigator.geolocation.watchPosition(). This will call your success or error handler functions each time the device receives a position update, rather than you needing to ping it every 20 seconds to see if it has changed.
With regard to page changing, so long as you’re using a multi-page template, then the handler function should get called while navigating to and from any sub-pages.
Here’s a JS fiddle illustrating this
Hope this helps!

stellar.js not working with dynamically loaded elements via AJAX

I'm using the fantastic Stellar.js (http://markdalgleish.com/projects/stellar.js/) for parallax on a recent project, but I've run into a challenge:
Stellar isn't noticing when I change content via AJAX (in this case loading in new div's from an html file and using jQuery's replaceWith method). So, my new elements have no parallax, even though they have stellar data attributes.
I've tried calling the .stellar function on my window again after the AJAX is complete, but it doesn't do anything.
How can I get Stellar to correctly apply parallax to the new AJAX'd in elements?
I know this question was posted a long time ago has been accepted, but for me the solution above did not work, so I just wanted to share this which worked for me.
After you AJAX call has been successful you can call Stellar's refresh function like so:
$.stellar('refresh');
Here is the full code:
$.ajax({
type: 'GET',
url: ajaxUrl
}).done(function(data) {
$(targetElement).html(data);
$.stellar('refresh');
}).fail(function() {
// Do something else
});
I found that I can run this code in my jQuery AJAX callback and Stellar will then correctly apply parallax to my new AJAX'd in elements:
$(window).data('plugin_stellar').destroy();
$(window).data('plugin_stellar').init();
I know that the topic is old but I want to share the solution that I found, hoping that it will be useful for people who are still searching.
First create the function:
function init () {
$(window).data('plugin_stellar').refresh();
}
jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});
Second insert this line in your Ajax call:
// Reinitialise plugins:
init();

Automatically initialize rich text editor on top of all textarea's, including ones that are loaded via ajax

I'm developing an ajax heavy web app, and would like to have textarea's (with class="ui-richtext") automatically initialize TinyMCE.
This is easy for textarea's that are loaded normally, but how about for content that is loaded AFTER the fact using ajax?
I was thinking something along these lines: (i'm using jquery)
$("textarea.ui-richtext").live("ajaxComplete", function()
{
$(this).tinymce({...});
});
Unfortunately this doesn't seem to work. Any ideas?
This is my first post, let me know if I need to add more info
Live is limited to a small number of events.
You can do something like this though:
$.ajax({
url: 'url/here',
success: function(data){
var $data = $(data).("textarea.ui-richtext").tinymce();
$('#mydiv').append($data);
}
});

Categories