Turbolinks prohibiting Javascript appended class for background images - javascript

I am integrating a front end html theme with a Laravel app and I am running into an issue with turbolinks not allowing Javascript to append div classes. This is causing the background images to only be displayed on refresh.
<div class="intro-banner" data-background-image="/storage/images/hero.jpg">
<div class="container">
custom.js
/*----------------------------------------------------*/
/* Inline CSS replacement for backgrounds
/*----------------------------------------------------*/
function inlineBG() {
// Common Inline CSS
$(".single-page-header, .intro-banner").each(function() {
var attrImageBG = $(this).attr('data-background-image');
if(attrImageBG !== undefined) {
$(this).append('<div class="background-image-container"></div>');
$('.background-image-container').css('background-image', 'url('+attrImageBG+')');
}
});
} inlineBG();
// Fix for intro banner with label
$(".intro-search-field").each(function() {
var bannerLabel = $(this).children("label").length;
if ( bannerLabel > 0 ){
$(this).addClass("with-label");
}
});
// Photo Boxes
$(".photo-box, .photo-section, .video-container").each(function() {
var photoBox = $(this);
var photoBoxBG = $(this).attr('data-background-image');
if(photoBox !== undefined) {
$(this).css('background-image', 'url('+photoBoxBG+')');
}
});

It looks like this code is only run once: on the initial page load. To get it working for every page load, you will need to run it on turbolinks:load. As the script also appends elements to the page, you need to be careful that you don't end up with unnecessary duplicate elements. Turbolinks stores a copy of the page in its final state before a visitor navigates away. This cached copy will include any appended HTML. So be sure your code checks for the presence of the appended elements before appending, or remove the elements before they are cached.
The following takes the latter approach, by removing elements on turbolinks:before-cache:
/*----------------------------------------------------*/
/* Inline CSS replacement for backgrounds
/*----------------------------------------------------*/
$(document).on('turbolinks:load', function () {
$(".single-page-header, .intro-banner").each(function() {
var attrImageBG = $(this).attr('data-background-image');
if(attrImageBG !== undefined) {
$(this).append('<div class="background-image-container"></div>');
$('.background-image-container').css('background-image', 'url('+attrImageBG+')');
}
});
// Fix for intro banner with label
$(".intro-search-field").addClass(function () {
if ($(this).children("label").length) return "with-label";
});
// Photo Boxes
$(".photo-box, .photo-section, .video-container").css('background-image', function () {
return 'url('+$(this).attr('data-background-image')+')'
})
});
$(document).on('turbolinks:before-cache', function () {
$(".single-page-header, .intro-banner").each(function() {
$(this).children(".background-image-container").remove();
});
});
I have also tidied up some of the jQuery code. Many jQuery functions accept functions as arguments, which simplifies things somewhat, and removes the need to iterate over a jquery selection with each.
Finally, wrapping lots of snippets in $(document).on('turbolinks:load', function () {…} is not great practice as creates a dependency on Turbolinks, and if you ever decided to move to something else, you have to update every place where this is called. If you're feeling adventurous, you may want to create a mini-framework like the one I create here: https://stackoverflow.com/a/44057187/783009

Related

An AJAX Search Plugin is removing my Event Listeners from an 'Accordion' style list

I'm using Search & Filter pro WP plugin for the ease of a client using it.
I've created a results page and filter on a demo site (for testing) that works fine but I know the categories will get large on the real site. So I turned the plugins' filters into an Accordion style list.
It works fine until certain searches reload all those filter results with AJAX and they remove my event listeners (which are sitting on elements for the moment, I know it's not ideal but for now I just want to see if it could work).
I imagine because my script has already been parsed when the DOM loaded, the AJAX from the plugin is just redefining those elements and they are then missing the Event Listeners or something.
Any help would be appreciated.
Here's my script:
<?php
add_action( 'wp_footer', function () { ?>
<script>
const clicker = document.querySelectorAll('#search-filter-form-4346 > ul > li > h4');
// looping through the <h4> elements and adding an event listener onto each, the class toggle just adds an animation to a pseudo-element spinner
for (let i = 0; i < clicker.length; i++) {
clicker[i].addEventListener("click", function() {
this.classList.toggle("open-filter-dropdown");
console.log('EL was created');
// declaring the <ul> as a variable
const openFilterPanel = this.nextElementSibling;
// animating the <ul> elements max-height
if (openFilterPanel.style.maxHeight) {
openFilterPanel.style.maxHeight = null;
} else {
openFilterPanel.style.maxHeight = openFilterPanel.scrollHeight + "px";
}
console.log('openFilterPanel style is changed');
});
}
</script>
<?php } );
I'm pretty new to javascript, I get the basic concepts but this kind of an interference is above my head. I tried refactoring my code, forcing the page to refresh and other such measures. None of these work very well. I also thought I could use a 'loadend' event on the document to re-add my ELs but that didn't work either.
Hoping there is a workaround here, otherwise I might have to find another solution or plugin.
Thanks in advance!

JavaScript only being called once in Squarespace

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.

jquery offset top wrong value, but gets right on page resize

I want to achieve a sticky menu like the left navigation on this page: http://getbootstrap.com/2.3.2/scaffolding.html.
My menu is a nav element with position:relative (I tried static as well) that goes fixed when it reaches the top of the viewport.
here's my function:
$(document).ready(function() {
function stickyNav() {
var elementPosition = $('nav').offset();
console.log(elementPosition);
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('nav').addClass("sticky");
} else {
$('nav').removeClass("sticky");
}
});
}
stickyNav();
}); //document ready
the console.log(elementPosition); returns an offset top of around 1200px on page load, which is wrong. But if i resize the page, the value changes to around 650px which is the correct offset top and the function does what it is supposed to be doing.
I've looked around and found out that offsetp top maybe wrong when it's on hidden elements, or it has issues with margins but I actually don't have any complex structure here, just a single visible nav element .
any help on figuring this out would be much appreciated! thanks!!
jQuery(document).ready handler occurs when the DOM is ready. Not when the page is fully rendered.
https://api.jquery.com/ready/
When using scripts that rely on the value of CSS style properties,
it's important to reference external stylesheets or embed style
elements before referencing the scripts.
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.
So if you're using stylesheets that are loaded AFTER the script in question, or the layout of the page depends on image sizes, or other content, the ready event will be hit when the page is not in its final rendering state.
You can fix that by:
Making sure you include all stylesheets before the script
Making sure the CSS is more robust, and doesn't depend that much on content size (such as images)
Or, you can do this on window load event.
Edit:
If you want to make your script dependent on more than one async event (like the loadCSS library), use this:
var docReady = jQuery.Deferred();
var stylesheet = loadCSS( "path/to/mystylesheet.css" );
var cssReady = jQuery.Deferred();
onloadCSS( stylesheet, function() {
cssReady.resolve();
});
jQuery(document).ready(function($) {
docReady.resolve($);
});
jQuery.when(docReady, cssReady).then(function($) {
//define stickyNav
stickyNav();
});
You can add a check to see if your CSS has loaded by setting a style tag in your document which shows a test element, and then overwrite this in your CSS file to hide it. Then you can check the status of your page by checking this element. For example...
In your HTML:
<div id="loaded-check" style="display:block; height:10px; width:10px; position:fixed;"></div>
In your CSS:
#loaded-check { display:none; }
In your jQuery script:
var startUp = function() {
var cssLoaded = $('#loaded-check').is(':visible');
if (cssLoaded) {
$('#loaded-check').remove();
doOtherStuff()
}
else {
setTimeout(function() {
startUp();
}, 10);
}
}
var doOtherStuff = function () {
//bind your sticky menu and any other functions reliant on DOM load here
}

Conditionally triggering slide and hide javascript events

I added some hide and slide functions to a website so that as each product attribute was selected the next one would slide out. This worked fine until the customer added additional attributes to SOME products. The additional attribute is causing me problems because i can't add a second slide function trigger without making it trigger two functions on these products.
The original code i used is
$('.wrapperAttribsOptions11').hide();
$('.sizeRadio').click(function () {
$('.wrapperAttribsOptions11').slideDown(800);
});
The client then added an attribute id4 so i added
$('.wrapperAttribsOptions4').change(function () {
$('.wrapperAttribsOptions11').slideDown(800);
});
But this means that on pages where BOTH attributes are in use option11 is sliding down when .sizeRadio is clicked and not when option4 is changed.
In short, is it possible to make it function so that if .wrapperAttribsOptions4 is present then
$('.sizeRadio').click(function () {
$('.wrapperAttribsOptions11').slideDown(800);
});
is ignored.
I hope that's clear enough.
I resolved this by using
if ($('.wrapperAttribsOptions4').length != 0) {
so the whole code segment becomes
$('.wrapperAttribsOptions11').hide();
if ($('.wrapperAttribsOptions4').length != 0) {
$('.wrapperAttribsOptions4').change(function () {
$('.wrapperAttribsOptions11').slideDown(800);
});
}else
$('.sizeRadio').click(function () {
$('.wrapperAttribsOptions11').slideDown(800);
});

jQuery masonry - call method after masonry reload

I use Twitter Bootstrap and jQuery Masonry for a new site in developement. I append new elements to the container of masonry.
The elements are neither appended or prepended to existing children but in inserted in between them, depending on a sorting order like this:
var elem = $(boxes[rand2]);
$(".post").each(function(i){
if(parseFloat($(this).data("weight"))<=weight){
elem.insertBefore(this);
return false;
}
else if (i == $(".post").length - 1) {
elem.insertAfter(this);
return false;
}
});
This works perfect so far. What I'd like to achieve is that the elements only display when they reached their destination place. I don't want to disable animations, but the space for the new element should appear (empty) and only when everything is re-arranged through masonry the new element should appear.
I thought there would be a callback-action that fires after reload like this:
$('#posts').masonry('reload',function(){
alert('re-aligning finished');
});
but that doesn't work, it fires to early.
So for the moment, I did
$('#posts').masonry('reload',function(){
window.setTimeout(showElem,500);
});
function showPosts(){
$('.post').show();
}
and that seems to work - but a fixed 500ms timeout is not a real beautiful solution...
So, any suggestions?
I'm guessing you're already using jQuery. Perhaps the use of deferred objects could be useful.
Could you do it later after document loads?
(function($) {
$(document).ready(documentReadyFunction);
$(window).resize(windowResizeFunction);
$(window).load(windowLoadFunction);
function documentReadyFunction() {
//your inserted html here
}
function windowResizeFunction() {
//resize here
}
function windowLoadFunction() {
//do masonry here
}
})(jQuery);

Categories