Run jQuery only when previous page was homepage

92 Views Asked by At

Basically the homepage has the CSS the JSFiddle starts with, and I want the inner pages to animate to their new CSS class ONLY when visited after the homepage.

<div class="container">
  <div>
    Thank you for your assistance!
  </div>
</div>

<style>
.container {
    padding: 100px 0;
    background: #ccc;
    text-align: center;
}

.container div {
    background: #eaeaea;
    width: 200px;
    height: 200px;
    margin:0 auto;
    text-indent: -9999px;
}

.container.inner,
.container.inner div {
    transition: all 0.75s ease-in;
}

.container.inner {
    padding: 10px 0;
}

.container.inner div {
    width: 100px;
    height: 100px;
}
</style>
<script>
jQuery( document ).ready(function() {
    setTimeout(function() {
        if ( jQuery(".home").length == 0  ) {
            jQuery('.container').addClass('inner');
        }
    }, 500 );
});
</script>

I imagine I need to use a cookie or two to determine if the previous page was the homepage and another to apply CSS without delay or animation if the previous page was an inner page.

2

There are 2 best solutions below

0
On BEST ANSWER

I ended up using PHP to determine the document referrer. Thank you @Jai for pointing me in the right direction. I placed the jQuery that changes the CSS inside a separate file and I call that js file whenever the referrer is "index.php" or "/"

Here's the exact code I used (on WordPress functions.php)

$homePagePaths = array (
  '/index.php',
  '/'
);

$parts = parse_url($_SERVER['HTTP_REFERER']);
if (empty($parts['path']) || in_array($parts['path'], $homePagePaths)) 
  wp_enqueue_script( 'inner-animation', 
  get_stylesheet_directory_uri() . '/js/inner-animation.js', 
  array('jquery'), '', true )
;
2
On

document.referrer is something you want to look at:

if(document.referrer.indexOf('home')){
   // apply the addClass here then.
}

Note:
document.referrer only holds the last page visited.