Execute code after the page has finished loading, excluding instances of page refresh

I have a specific jquery function that I need to execute only the very first time a page loads, not upon refreshing the page.

Here is the code snippet:

$(window).on("load",function() {
    $("#logo-black").typed({
        strings: ["Nothing^450&Co^250.^500", "^800__^400&Co^600."],
        typeSpeed: 70,
        backSpeed: 100,
    callback: function() {
        $(".typed-cursor").css("display", "none"),
        setTimeout(function(){
            $('.main-load').toggleClass('main-load-active'),
            $('.nav-text').toggleClass('nav-text-active');
        },400),
        $('.nav-reveal').toggleClass('nav-reveal-active');
        }
    });
});

A few important points to consider: -I am utilizing barba.js, which introduces content dynamically through AJAX requests.

The following code initializes barba.js for my project:

initFullpagePlugin();

function initFullpagePlugin (parentElement) {
var element;

element = parentElement ? $('#fullpage', parentElement) : 
$('#fullpage');

if (element.length) {

  // Removes old fullPage.js object from memory and DOM elements
  if ($.fn.fullpage.destroy) {
    $.fn.fullpage.destroy('all');
  }
  element.fullpage({
    //Scrolling
    autoScrolling:false,
    scrollingSpeed: 2500,
    easing: 'swing',
    fitToSection: false
  });
}
}

document.addEventListener("DOMContentLoaded", function() {
if (!('webkitClipPath' in document.body.style)) {
alert('Sorry, this demo is available just with webkitClipPath. Try with 
Chrome/Safari.');
}

Barba.Pjax.init();
Barba.Prefetch.init();


var FadeTransition = Barba.BaseTransition.extend({
start: function() {
/**
 * This function is automatically called as soon the Transition starts
 * this.newContainerLoading is a Promise for the loading of the new 
container
 * (Barba.js also comes with an handy Promise polyfill!)
 */

// As soon the loading is finished and the old page is faded out, let's 
fade the new page
Promise
  .all([this.newContainerLoading, this.fadeOut()])
  .then(this.fadeIn.bind(this));
},

fadeOut: function() {
/**
 * this.oldContainer is the HTMLElement of the old Container
 */

return $(this.oldContainer).animate({ opacity: 0 }).promise();
},

fadeIn: function() {
/**
 * this.newContainer is the HTMLElement of the new Container
 * At this stage newContainer is on the DOM (inside our #barba-
container and with visibility: hidden)
 * Please note, newContainer is available just after 
newContainerLoading is resolved!
 */
document.body.scrollTop = 0;
var _this = this;
var $el = $(this.newContainer);

$(this.oldContainer).hide();

$el.css({
  visibility : 'visible',
  opacity : 0
});

initFullpagePlugin($el);

$el.animate({ opacity: 1 }, 400, function() {
  /**
   * Do not forget to call .done() as soon your transition is finished!
   * .done() will automatically remove from the DOM the old Container
   */
  _this.done();
});
}
});

/**
* Next step, you have to tell Barba to use the new Transition
*/

Barba.Pjax.getTransition = function() {
/**
 * Here you can use your own logic!
 * For example you can use different Transition based on the current 
 page or link...
 */

 return FadeTransition;
 };
});

$('.no-click').on("click", function(e) {
e.preventDefault();
});

As an example, take a look at this design studio that features an animation when initially loading the home page, but does not repeat upon page refresh. (Please note that this behavior is primarily observed on the mobile version, resembling what I aim to achieve. The element being animated exists on every page, so ensuring it triggers only on first load & exclusively on index.html is my goal.)

Any assistance, suggestions, or constructive criticism are welcomed!

Answer №1

When it comes to code running on the user's device, it operates in a stateless manner between page reloads. To maintain state information across different loads, you have two options:

  • Maintain session data on the server side.
  • Utilize cookies or local storage in the user's browser.

Answer №2

One way to achieve this is by manipulating the server side.

Verify the referrer header. If it is absent or different from the current request URL, trigger the jquery function to execute upon page loading in the browser. However, if it matches the current request URL, prevent the jquery script from running.

If the webpage is completely static and lacks such capabilities, consider referring to Chase's solution.

Answer №3

Utilize the transitionCompleted function for loading your script.

Barba.Dispatcher.on('transitionCompleted', function(currentStatus, prevStatus) {

    if (prevStatus) {
        setTimeout(function() {

            // execute your script

        }, 1000);
    }

});

Keep in mind that the event transitionCompleted in barba.js triggers every time a new page is loaded.

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

Activating Parent and Sub-menu classes: A step-by-step guide

Issue at hand: Identifying Parent and Sub-menu classes as active. Essentially, I am working with a json array that represents my current page layout. I am trying to loop through the array and determine if it matches the current page. However, I am facing ...

Is Ajax better suited for post or get requests?

My main use for Ajax has been as a POST method to handle tasks. However, I recently attempted to open a simple login page within a DIV (and successfully did so). The issue arose when I added the following PHP code: <?php if (isset($_POST)) { } else { ...

generate a cookie within a pop-up window

Can someone help me figure out why my Modal Window with a cookie to display only once isn't working? I followed this tutorial at . Here is the link to my website: Here is my code: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" a ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Tips for setting an image as the background on various mobile screen sizes

Is there a way to set an image as a background that will work effectively with multiple different mobile screen resolutions without distorting or cropping the image? For example, if I want the image to display correctly on both iPhone4 and iPhone6 without ...

"Using HTML to assign a unique identifier to an image within

Apologies in advance for any errors as I am relatively new to html. I am attempting to construct a table with images that have onclick events, so that each clicked seat is tracked and its id is added to a list to change the class. Each image has been give ...

The customization of a Wordpress theme is causing an issue: the CSS class cannot be

I have been trying to customize a free version of a popular WordPress theme called EmpowerWP. Despite searching through all the files on the website, I have been unable to find a specific CSS class that I am looking for. As a result, I am considering two ...

Unexpected behavior observed with LitHTML when binding value to input type range

Currently, I am working on an implementation that involves using range inputs. Specifically, I have two range inputs and I am trying to create a 'double range' functionality with them. The challenge I am facing is related to preventing one slider ...

Is using readonly attribute for HTML inputs a security concern?

Is it reliable to trust the data from an html input field set to readonly? What exactly is the purpose of using a readonly field in a form? I understand that disabled fields are not included in $_POST, but what about readonly fields? I need a way to have ...

Looking for assistance with CSS positioning techniques

Creating a dropdown list with a caret icon for each item is my goal, but I'm facing some challenges. Here's the code snippet of the div structure: <div class="class-to-div1" id="{{ div.id }}" data-cardsnum="{{ div.num }}"> <div clas ...

Expanding Your jQuery Library from a Content Delivery Network

As of now, I have a jQuery hosted on my FTP along with other web files. YSlow recommends using a CDN for jQuery. However, I am wondering how I can extend that jQuery. Is it possible to add custom functions to it without being able to edit the original co ...

Move the scroll event binding from the parent element to the child element

I'm working on an HTML page with the following structure: <div class="parent"> <div class="child1"> <div class="child2"> </div> </div> </div> Currently, I have a scr ...

What is the best way to combine JavaScript objects with identical values?

We have a task to compare each input key with others to find any common values. If there are common values, we need to concatenate them together and display the pairs. If no common values are found, then an empty array should be displayed as output. inpu ...

Tips for displaying or concealing data in table cells in Google Charts

Using a Google charts table to display server exceptions, but the errors are too long for cells. How can I show only an excerpt of error messages in each cell with a + expansion sign for full details in a modal box on click? I have successfully implement ...

Trouble with Vue: Sibling components unable to communicate

I am encountering an issue while trying to pass data from typing.js to ending-page.js within sibling components. Despite my efforts, the emit and event hubs are not functioning as expected. However, emitting from typing.js to the parent component works sea ...

Learn how to dynamically import and load components in VueJS while rendering a list

I am currently rendering a list. <div v-for="msg in messages"> <div v-if="msg.type==='component'"> <component v-bind:is="getComponent(msg.component)" :data="msg.data" :text="msg.text"></component> </div> ...

jQuery Gallery for uploading multiple images

Can you suggest the top jQuery multiple image uploader that you would recommend? ...

Generate an array consisting of characters within a designated range

I recently came across some Ruby code that caught my attention: puts ('A'..'Z').to_a.join(',') The output was: A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z I'm curious if there is a similar way to achieve this ...

Uh oh! AngularJS just threw an error: Uncaught TypeError - angular.service is not a function. It happened in taskService.js

I've run into some issues with AngularJS, even though I have imported all the necessary libraries. Specifically, I am encountering the following errors: Uncaught TypeError: angular.service is not a function at taskService.js:2 taskFactory. ...

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...