My webpage is full ajax navigation, when clicking through various links in the page and I have jQuery code being used on the page but it fails to load when clicking ajax links. I have tried using on. live. delegated. but they all did not work.
I used the below code I found on here to reload my jquery code
//function initialise(){
$('.youtube iframe').each( function(){
// return if we're dealing with google ads iframe
if ( typeof $(this).attr('src') == 'undefined' ) return;
var $this_video = $(this),
src_attr = $this_video.attr('src'),
wmode_character = src_attr.indexOf( '?' ) == -1 ? '?' : '&',
this_src = src_attr + wmode_character + 'wmode=opaque&rel=0&showinfo=0&modestbranding=1&theme=light';
$this_video.attr('src',this_src);
} );
};
// $(document).ready(function(){
initialise();
});
// $(document).ajaxComplete(function () {
initialise();
});
But when I use this code the iframe on the page seems stucked in a loop.I assume it's stuck in the loop because the ajax call checks for an update every few seconds but I want to know how I can apply my jQuery iframe code and not have it reloaded every few seconds
Related
I have some custom JavaScript on my SquareSpace site that manipulates Product titles beyond what you can do with SquareSpace's default style editor. It works when initially loading the page (https://www.manilva.co/catalogue-accessories/) but if you click on any of the categories on the left, the styling resets to the default.
I'm assuming the JavaScript is being overwritten by the SquareSpace style, but I can't figure out why. Perhaps I'm calling the function in the wrong place?
Any suggestions would be helpful.
Thanks!
Current code:
document.querySelectorAll(".ProductList-filter-list-item-link".forEach(i=>i.addEventListener("click", function()
{
var prodList = document.querySelectorAll("h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
var text = prodList[i].innerText;
var index = text.indexOf('-');
var lower = text.substring(0, index);
var higher = text.substring(index + 2);
prodList[i].innerHTML = lower.bold() + "<br>" + higher;
});
The source of your problem is that your template has AJAX loading enabled. There are currently a couple generally-accepted ways to deal with this as a Squarespace developer:
Disable AJAX loading
Write your javascript functions in a
manner that will run on initial site load and whenever an "AJAX load" takes place.
Option 1 - Disable AJAX:
In the Home Menu, click Design, and then click Site Styles.
Scroll down to Site: Loading.
Uncheck Enable Ajax Loading.
Option 2 - Account for AJAX in Your JS
There are a number of ways that developers approach this, including the following, added via sitewide code injection:
<script>
window.Squarespace.onInitialize(Y, function() {
// do stuff
});
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// myFunction2(); , etc...
// Reinit. the fn on each new AJAX-loaded page.
window.addEventListener("mercury:load", myFunction);
})();
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// Reinit. the fn on each new AJAX-loaded page.
new MutationObserver(function() {
myFunction();
// myFunction2(); , etc...
}).observe(document.body, {attributes:true, attributeFilter:["id"]});
})();
</script>
Each of those works for most of the latest (at time of writing) templates most of the time. Each of those have their advantages and disadvantages, and contexts where they do not work as one might expect (for example, on the /cart/ page or other "system" pages). By adding your code within the context of one of the methods above, and ensuring that the code is of course working in the desired contexts and without its own bugs/issues, you will have your code run on initial site load and on each AJAX page load (with some exceptions, depending on the method you use).
Your problem is the page does not reload when clicking a button on the left, just some elements are removed, added and replaced. The changed elements will not be restyled. You will need to re-run your JavaScript after one of those buttons is clicked. Perhaps something like this:
document.querySelectorAll(
".ProductList-filter-list-item"
).forEach(
i=>i.addEventListener(
"click", ()=>console.log("hello")
)
)
where you replace console.log("hello") with whatever resets your formatting.
I'm developing a website which involves the user being able to navigate to different parts of a page from other pages using # values in the address bar.
I have written a jQuery function to handle the scrolling here:
jQuery.fn.scrollToDiv = function(navheight)
{
if (!navheight)
{
navheight = 30;
}
var offset = this.offset();
var offsetTop = offset.top;
var totalScroll = offsetTop-navheight-27;
$('body,html').animate({
scrollTop: totalScroll
}, 500);
}
And I am calling the function in 2 different scenarios; when the user clicks a link where the object is on the current page, and when the user clicks a link that takes them to another page before scrolling to the element. See below:
When you are on the page:
$('.gotoPage').on('click', function(e)
{
e.preventDefault();
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPath != '' && sPath != 'home')
{
var href = $(this).attr('href');
handleScroll(href);
}
});
and when you are not on the page:
$(document).ready(function(e)
{
var target = window.location.hash;
if (target != '')
{
$(target).scrollToDiv(30);
}
});
It works perfectly when you are on the page and click the link, however when you're not on the page, it takes you to the subsequent page as you'd expect but it doesn't then scroll to the required element.
Let me know if you need any more information
Thanks in advance
EDIT: Added function handleScroll(target)
function handleScroll(target)
{
if (target != '')
{
$(target).scrollToDiv(30);
}
}
Following your comment:
I've noticed when refreshing the page is that it scrolls down then
jumps back to the top of the page
It seems that your script does work, but something affecting it afterwards.
I believe that there are some resources as additional css codes or images that aren't being taken in account when the scroll animation takes effect and since that function works by top offset - you must be sure that you're using it after all the resources that might affect the document's height or element's offset, are being loaded.
Therefore, instead of using your script in .ready(), use .load().
.ready() vs. .load()
In most cases, the script can be run as soon as the DOM hierarchy has
been fully constructed. The handler passed to .ready() is guaranteed
to be executed after the DOM is ready, so this is usually the best
place to attach all other event handlers and run other jQuery code.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
The idea is each page has the same header and footer exactly, but each page has inner content that will change each page load
<header>blah blah blah</header>
<div id="main-content">Changes Each Page, but with links like Go to Another Page with smooth animation</div>
<footer>blah blah blah</footer>
I have written this script based off an earlier version I saw somewhere, however I am having an issue where no scripts are being fired. The site's overall scripts are all loaded on the initial page load, and I just need the scripts to be re-run each time you click on a link, that way I can have the seamless effect of the site pages loading inside the page, and adding custom CSS animations when each custom page loads.
var newHash = '',
$mainContent = $('#main-content');
$(".ajaxify").click(function(event) {
event.preventDefault();
newHash = $(this).attr('href');
history.pushState(null, null, newHash);
$mainContent.load(newHash + " #main-content > *");
return false;
});
I attempted to add a .getscript block when ajax is completed, but I found that it starts making the page loads really heavy and starts firing off errors.
$(document).on("ajaxComplete",function(){
$.getScript( "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" );
$.getScript( "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" );
$.getScript( "../js/libraries.js" );
$.getScript( "../js/footer.js" );
});
What am I missing?
Big thanks to beercohol, he set me on the right direction. I didn't need to reload the whole javascript stack from the head each time; just the javascript in the footer. This solved so many issues at once.
EDIT: I also discovered that by changing it to "delegate" vs onclick, I dont' need to reload the initial ajax script again. Very handy and keeps the pages light.
Final Code example is this:
var newHash = '',
$mainContent = $('#main-content');
$('body').delegate(".ajaxify", "click", function() {
event.preventDefault();
$("html, body").animate({ scrollTop: 0 }, 500);
newHash = $(this).attr('href');
history.pushState(null, null, newHash);
$mainContent.delay(500).load(newHash + " #main-content > *");
return false;
});
$(document).on("ajaxComplete",function(){
jQuery.get('/js/footer.js', function(data) { eval(data); })
});
Assuming your scripts are loaded in your header, then you don't need to reload them with .getScript. That would just keep adding them into the page again for every link you click!
Your main function looks mostly correct - although it seems to be missing the first line - but the .load doesn't look quite right. Try something like this:
$(document).ready(function() {
var newHash = '',
$mainContent = $('#main-content');
$(".ajaxify").click(function(event) {
event.preventDefault();
newHash = $(this).attr('href');
history.pushState(null, null, newHash);
$mainContent.load(newHash + ' #main-content');
return false;
});
I tried with this code but, didnĀ“t worked.
<a href="http://altodesign.pt/#portfolio" onClick="loadintoIframe('myframe,'portfolio/mmteam.html');">
you can try something like this
a href="javavcipt:document.getElementById('myframe').src = 'portfolio/mmteam.html';"
I would never use javascript ...
I have had a look into your webpage (plenty to learn, like add scripts to the end of the page, create a global javascript object to hold all website actions, etc ... but that's not the question)
I could see that, even thought you jump to #CONTACTOS you are not making the use of the hash at all... and you should!
using the hash would let you do things like:
http://altodesign.pt/#portfolio-cooptaxis
and that would jump to portfolio anchor and load the cooptaxis.html into the iframe and you stoped using javascript:loadintoIframe('myframe', 'portfolio/mmteam.html') at all, as that will cause Google Analytics and Crawlers not to follow up your links for example ...
your method could be something simple like
$(function() {
// let's see if we have an hash on the page
var hash = document.location.hash;
if(hash.length > 0) {
if(hash.instr('-') >= 0) {
// supposing will have only one char '-'
var img = hash.split('-')[1];
// let's remove the frame info from the hash
hash = hash.split('-')[0];
// there's a call to load into the iframe, let's load it
$("#myframe").attr("src", "portfolio/" + img + ".html")
}
// let's fly
jumpTo(hash);
}
// let's disable the anchor links by default and use the hash
$("a[href^=#]").click(function() {
// for all links that start with the hash, let's...
document.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function() {
// everytime the hash changes let's fly
jumpTo(document.location.hash);
});
});
function jumpTo(anchor) {
var a = $("a[name='" + anchor.replace('#','') + "']"),
pos = 0;
if(a.length > 0) {
// we have found the anchor, let's grab it's top position
pos = a.position().top;
}
// if we got here and pos === 0, we did not found the anchor
// for the given hash... maybe the user is playing around ...
// and we shall fly
$('body,html').animate({
scrollTop: pos
}, 800);
}
justthis will allow you to avoid using javascript to jump your links, as all they now have to have is simple: Portfolio
Let we say that you have page1.html in-which a link to page2.html you want it to be opened in an iframe in page1.html
in page1.html
link
<iframe name="iframe-name"></iframe>
Then you are able to add any anchor you want. It is just a matter of naming your iframe and then targeting it in the link!
I have a page which displays multiple blocks with results details. Inside each block I have some <a> tags with thickbox jQuery plugin attached: class="thickbox"
Here is an example of one kind of ampersant tag:
<a class="thickbox" title="Please Sign In" href="userloginredir.php?height=220&width=350&deal=3">
Problem comes when I added a jQuery pagination to the page because of too many results displaying on the page.
The div component with the results inside is updated through ajax load() event.
Below is the pagination script:
$(document).ready(function(){
//References
var pages = $("#menu_deals li");
var loading = $("#loading_deals");
var content = $("#content_deals");
//show loading bar
function showLoading(){
loading
.css({visibility:"visible"})
.css({opacity:"1"})
.css({display:"block"})
;
}
//hide loading bar
function hideLoading(){
loading.fadeTo(1000, 0);
};
//Manage click events
pages.live('click',function(){
//show the loading bar
showLoading();
//Highlight current page number
pages.css({'background-color' : ''});
$(this).css({'background-color' : 'yellow'});
//Load content
var pageNum = this.id;
var targetUrl = "ajax_search_results.php?page=" + pageNum + "&" + $("#dealsForm").serialize() + " #content_d";
content.load(targetUrl, hideLoading);
});
//default - 1st page
$("#1").css({'background-color' : 'yellow'});
var targetUrl = "ajax_search_results.php?page=1&" + $("#dealsForm").serialize() + " #content_d";
showLoading();
content.load(targetUrl, hideLoading);
});
When I added pagination (code above), the thickbox events are not recognized anymore and instead of poping out a window with the login form inside it opens the results in new page (is acting like clicking on a normal link)
From my jQuery knowledge this means that the components are not defined in the DOM because the content is updated after document ready triggered.
I'm trying to bind the load event with something like this:
content.bind('load', ???);
But I don't know how to pass the load params, targetUrl and the callback function hideLoading, when binding the load event.
Please help me out in this matter, it already took me more time than possible allowed.
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
call that in the callback of the ajax.
You have used the hideLoading function as the callback, instead replace it with this where you intialise the thickbox and also hide the loading.
content.load(targetURL, function(){ tb_init('a.thickbox'); hideLoading(); });