Run function after page load but NOT refresh - javascript

I have a jquery function I want to run ONLY when a page is loaded the first time, not after a refresh.
Here's the code:
$(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 things to note:
-I'm using barba.js, so content is added/removed via AJAX.
Code that initializes barba.js for my project:
initFullpagePlugin();
function initFullpagePlugin (parentElement) {
var element;
element = parentElement ? $('#fullpage', parentElement) :
$('#fullpage');
if (element.length) {
// Destroys old fullPage.js object in memory,
// removes elements from DOM
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();
});
For instance, this design studio has an animation that runs when you first load the home page, but not after a refresh. (NOTE: this seems to only apply to the mobile version, but it's what I'm trying to achieve. The element I'm animating is present on every page, so making sure it only fires on first load & ONLY on the index.html is something I'm shooting for)
Any help/suggestions/constructive criticism is appreciated!

Code executed on the client is stateless between loads. If you want to remember state from page load to page load, you can either:
Track the session on the back end.
Use cookies/local storage in the client's browser.

You can easily do this from the server side.
Check the referrer header. If it is not present, or it is not the same as the URL in the current request, go ahead and emit the jquery function so that it will execute when the page is loaded into the browser. When it is the same as the URL in the current request, just withhold the jquery script so that it can't run.
If the page is 100% static and you can't do anything like this, well, see Chase's answer.

You can use the transitionCompleted function to load your script.
Barba.Dispatcher.on('transitionCompleted', function(currentStatus, prevStatus) {
if (prevStatus) {
setTimeout(function() {
// call your script
}, 1000);
}
});
Remember that the barba.js event transitionCompleted is fired each time a new page is loaded.

Related

Need help Converting a jQuery event to a Drupal Behavior

I have a Drupal 7 web site that is using jQuery animations to fadeIn div tags. I need an event to capture a fadeIn when it is completed. I have found a sample jQuery example that does what I need it to, but I have not been able to successfully convert it to a Drupal 7 behavior and I'm not quite sure what I might be missing.
Fiddle Example
Below is my Drupal JS file, fadeInEvent.js.
Drupal.behaviors.fadeInEvent= {
attach: function (context, settings) {
var _old = jQuery.fn.fadeIn;
jQuery.fn.fadeIn = function() {
var self = this;
_old.apply(this.arguments).promise().done(function(){
self.trigger('fadeIn');
});
};
jQuery('.tab-pane').bind('fadeIn', function() {
alert('fadeIn Done.');
});
}
};
In the above JS code, I never get my alert that the fadeIn has finished on the item I have selected.
Firs of all, while using jQuery in noconflict mode, you may use a closure to access it by $
(function($) {
// jQuery code using $ object.
}(jQuery));
Regarding the .fadeIn(), consider my snippet:
/**
* $.fn.fadeInNew plugin for triggering 'fadeInDone', when .fadeIn is done.
*
* #param speed
* #param easing
* #param callback
* #returns {$.fn}
*/
$.fn.fadeInNew = function(speed, easing, callback) {
var self = this;
self.animate({
opacity: "show"
}, speed, easing, function() {
self.trigger('fadeInDone');
if ($.isFunction(callback)) {
callback.apply(self);
}
});
return self;
}
$('.tab-pane').on('fadeInDone', function() {
alert('Alarm!');
});
$('.button').on('click', function(e) {
$('.tab-pane').fadeInNew();
});
.tab-pane {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab-pane">Have a good day!</div>
<button class="button">Show something!</button>
Since I don't really like the idea of overriding the native methods of any libraries, I have made a plugin .fadeInNew(), which will trigger custom fadeInDone event on the element. The code behind animation is almoast the same as in native implementation see the source here.
Also, you don't need to use Drupal.behaviors to define something like that. You should use attach only for things that are being loaded with Drupal's ajax framework, see includes/ajax.php

PJAX/DJAX- rerun scripts after pjax load

I'm using RequireJS to structure my JS and DJAX (basically PJAX) as a way to dynamically load content without a full page reload.
The issue I have is that after DJAX has finished loading the content I need to rerun my scripts (e.g. a script that adds multiple images into a carousel) so that the new page renders correctly. I thought the best way to do this would be to simply rerun the function I'm running on $(document).ready(); but I'm getting this output in the console:
Uncaught TypeError: Cannot read property 'djaxLoad' of undefined
which is referring to this line in load-posts.js
bootstrap.init();
I'm guessing I'm writing something incorrectly.
Here is bootstrap.js which is my main file which fires on document.ready and initialises all my modules
require(['base/responsive', 'base/main-menu', 'base/social-share', 'base/randomise-colours', 'base/infinite-scroll', 'base/load-posts', 'base/image-fade', 'base/carousel', 'base/misc'],
function(responsive, main_menu, social_share, randomise_colours, infinite_scroll, load_posts, image_fade, carousel, misc) {
var $ = jQuery;
function djaxLoad() {
//If page has JS (detected with Modernizr) then hide content until the
//doc is ready to avoid flash of unstyled content
$('#djax-container').css('display', 'block');
main_menu.init();
social_share.init();
randomise_colours.init();
load_posts.init();
image_fade.init();
infinite_scroll.init();
carousel.init();
misc.init();
responsive.init();
}
$(document).ready(djaxLoad);
}
);
And this is load-posts.js which handles DJAX for me. DJAX works, I just need to get the scripts to fire again.
define(['djax', 'base/bootstrap'], function(djax, bootstrap) {
var $ = jQuery,
$body = $('body');
return {
init: function() {
if($body.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.pjaxLinks();
},
pjaxLinks: function() {
//Initialise DJAX, but stop it from running on pagination links (URL is /page...)
$('body').djax('.updateable', ['page']);
//When clicking a djax link
$(window).bind('djaxClick', $.proxy(function() {
this.addLoader();
},this));
//When the new content has loaded in
$(window).bind('djaxLoad', $.proxy(function() {
this.removeLoader();
},this));
},
addLoader: function() {
$body.addClass('loader-visible');
},
removeLoader: function() {
$body.removeClass('menu-visible');
$('html, body').scrollTop(0);
function removeLoaderDelay() {
$body.removeClass('loader-visible');
bootstrap.djaxLoad();
}
setTimeout(removeLoaderDelay, 1000);
}
};
});
The djaxClick function runs on a link click, and the djaxLoad function runs after the content has been loaded in. I'm adding a loader overlay to the page, then removing it after the content has loaded in.
A bit late but for future reference: In the documentation at https://github.com/beezee/djax you'll find the djaxLoad-event. This is specifically made for your usecase. You can use it as follows:
$(window).bind('djaxLoad', function(e, data) {
// your scripts to run on ajax-calls
});
The site further explains: "the data object passed with the event contains the requested url, the page title for the requested page, and the contents of the requested page as a string".
$(window).bind('djaxLoad', function(e, data) {
var responseObj = $('<div>'+data.response+'</div>');
//do stuff here
});

Jquery function - on element

I have this jquery code, working 100%.
This is executing on every page load, when i import my js file in the html.
My question, how can i make use of this code, only when the element is present, or call it directly from the element itself? I have similiar functions, but, on html's that dont have specific elements, javascript execution halts. Sometimes because the html elements dont exist on that specific html file.
/**
* Message Box Display
*/
$(document).ready(function() {
$("#Message-Box" ).slideDown("slow", function() {
$("#Message-Box").addClass('Show');
setTimeout(function(){
$('#Message-Box').addClass('Hide');
}, 5000);
});
});
try something like this
$(document).ready(function() {
var msgbx = $("#Message-Box");
if (msgbx.length) {
msgbx.slideDown("slow", function() {
msgbx.addClass('Show');
setTimeout(function() {
msgbx.addClass('Hide');
}, 5000);
});
}
});
The function halting my script was this one:
/**
* Background-Audio
*/
$(document).ready(function() {
var audioTrack = document.getElementById("Background-Audio");
if(audioTrack)
{
audioTrack.volume = 0.05;
audioTrack.play();
}
});

How to find JS function name?

I have implemented on a website a picture gallery that does not allow (it seems) the auto sliding. So at the moment I have to push on a button to see the next picture. My purpose is to catch the function that allows to move to the next picture and to set a timeout to go to the next picture automatically.
How can I get the JS function name using Google Chrome developer tools?
Thank you
UPDATE
This is the Gallery script: http://tympanus.net/Development/ScatteredPolaroidsGallery/
I would like to implement auto sliding on it
source for code proposal from: https://github.com/codrops/ScatteredPolaroidsGallery/issues/4
(function() {
function autoSliding(timeout) {
var self = this;
clearTimeout(self.timeOut);
self.timeOut = setTimeout(function() {
self._navigate('next');
}, timeout);
}
new Photostack( document.getElementById( 'photostack-1' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
new Photostack( document.getElementById( 'photostack-2' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
}())
This should do the work
$('.navigate-next').click();
Or for auto scroll
setInterval(function(){$('.navigate-next').click();},1000);
Change 1000 for whatever you wish
If you are allowed to use jquery in your code, then, you can use $._data() method.
syntax is $._data($("selector of the element")[0], "events")
This will return an Object of all events bounded to that element. Then get the click event and call the handler attribute of the click event.

Number, hover (etc) effect not work after Ajax Load More

I'm using Drupal 7 and get my content with View module on page. And my pager Views Load More module. And my thumbnail effect hover, shadow etc. Image hover using this code:
var hoverImg = '<div class="hoverimg"></div>';
$(".thumb").each(function(){
$(this).children("div").each(function(){
$(this).find("a").append(hoverImg);
});
});
$(".thumb div").hover(function() {
$(this).find(".hoverimg").animate({ opacity: 'toggle' });
});
$(".thumb").hover(function() {
$(this).find("div").each(function(){
$(this).find(".shadow").fadeOut(500);
});
});
And getting number on my current thumbnail. This code:
var c = '';
var d = '';
$('.view-content div.views-row').each(function(){
c = 0;
d = 0;
var i = 1;
d = $(this).find('.thumbimg').length;
$(this).find('.thumbimg').each(function(){
sayi=i++;
$(this).append('<div class="img_no">0'+sayi+'</div>');
});
});
Everything is OK. All effects on start page. But when click Load More button, my effects can't work another page.
How do i solve this problem? Thanks.
The reason why it stops working is due to the hover function (and your other scripts/functions) only works on existing elements. So if you add something with ajax, it wont apply to that unless you reload the script after the ajax load.
Another option is to use live() or on() (for the hover part. On is the new version of live, added in jQuery 1.7).
Live and on listens for any existing or future elements.
A live script would look something like this:
$(".yourElement").live({
mouseenter:
function () {
// Do something
},
mouseleave:
function () {
// Do something
},
mousemove:
function () {
// Do something
}
});

Categories