Turbolinks not allowing the addition of JavaScript classes for background images

While trying to merge a front end html theme with my Laravel app, I encountered an issue with turbolinks that is preventing Javascript from appending div classes. This is resulting in background images only being displayed on page 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+')');
    }
});

Answer №1

Upon closer inspection, it appears that this code executes only once, specifically during the initial page load. In order to ensure it runs every time the page loads, it should be triggered on turbolinks:load. Additionally, since the script adds elements to the page, precautions must be taken to prevent redundant duplicate elements. Turbolinks preserves a copy of the final state of the page before a user navigates away, including any appended HTML. Therefore, it is essential for your code to check for existing appended elements before adding new ones or remove them prior to caching.

A more cautious approach involves removing elements using 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();
    });
});

In addition, I have optimized some of the jQuery code by utilizing functions as arguments, which streamlines the process and eliminates the need to iterate over a jquery selection using each.

Lastly, relying heavily on

$(document).on('turbolinks:load', function () {…}
for various snippets is not advisable as it creates a dependency on Turbolinks. Should you decide to transition to a different platform in the future, substantial updates would be required wherever this method is implemented. For a more versatile solution, you might consider developing a mini-framework akin to the one showcased here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display table rows that are hidden in an HTML/Angular toggle function

I am relatively new to Angular and I have a task of setting up a table. The dataset that I have is as follows:- data = [{rollno: 1,name: 'abc',subject: 'maths'}, {rollno: 4,name: 'xyz',subject: 'history'}, ...

I would like to retrieve my data using my personal API and have them displayed as checkboxes

https://i.sstatic.net/qPSqe.jpgHere is an excerpt of the progress I have made main.html (it's actually a form) <div class="form-group form-check-inline"> <input class="form-check-input" type="radio" name=& ...

Utilizing JSON data to populate a modal window in HTML

How can I incorporate JSON data into an HTML modal window? I have a set of 12 buttons, and when a user clicks on one, I want to display the corresponding month's information from a JSON file. let myJson; $(`button`).on(`click`, function() { let ...

How to Use CSS to Perfectly Align Form Elements in the Center of

No matter what I try, I just can't seem to get these form elements centered on the page using CSS. Here is my code snippet: http://jsfiddle.net/VJLst/1/ <style> #divQuizFillBlank { margin-left: auto; margin-right: auto; } #textQuizFill ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...

Prevent divs from jumping to a new line with the float property

I've been busy working on a responsive webpage and so far, everything is going smoothly. The only issue I'm facing is that when the browser window size decreases and reaches a certain point, the div elements jump to the next line. Take a look at ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...

What is the most effective method for organizing and handling uploaded files within my editing software?

I am currently developing a social blog that includes a JavaScript-based editor for users to create their own blogs. One of the main challenges I am facing is related to uploading files and its limitations. Currently, I am storing images uploaded by users ...

Avoid duplicate submissions while still enforcing mandatory fields

Let's start with a basic form that only asks for an email address: <form action="NextPage.php" method="post"> <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email"> <button type="submit">Subm ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

Tips for resolving the issue with "Text Animation"

Could someone please help with fixing this CSS animation? I want to align the text animation to the paragraph properly. I'm not confident if I am approaching this in the correct way, so if there is a simpler solution out there, I would appreciate lea ...

Would someone be able to clarify the purpose of this await useState React code?

Recently, I came across some React code that directly modifies the state, which goes against what I was taught. However, when I attempted to update it properly, the functionality broke. Clearly, an issue needs to be fixed, but before diving in, I'd li ...

JSON.Parse function does not return a valid value

I'm currently developing a polling system. Once a user submits their answer choice, I expect to receive JSON data containing all the answers for display purposes. Upon submitting the AJAX form, the JSON response is as follows: [{"answer_1":0,"answer ...

Invoking a function containing an await statement does not pause the execution flow until the corresponding promise is fulfilled

Imagine a situation like this: function process1(): Promise<string> { return new Promise((resolve, reject) => { // do something const response = true; setTimeout(() => { if (response) { resolve("success"); ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Transmit a base64-encoded image in an HTTP request to the server

I am currently working on sending a base64 image using the request npm module from a nodejs/express application to another REST API endpoint. Below is the code I am using: First, I have middleware set up using multer and datauri to upload the image in mem ...