Sam Tyurenkov Sam Tyurenkov - 29 days ago 10
PHP Question

Running resize logo script on wordpress

I'm trying to implement a custom logo shrink on a website, but I'm doing something wrong and can't locate the mistake. Maybe you can give a small advice.

So what I already did:

1.Child theme with style.css, functions.php, assets/js/my_shrinker.js

2.I added a function to load my-shrinker.js in functions.php

function shrinker() {
wp_enqueue_script( 'my_shrinker', get_stylesheet_directory_uri().'/assets/js/my_shrinker.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'shrinker' );


3.Added this code to perform shrink when scrolling in my-shrinker.js

function my_shrinker() {
window.addEventListener('scroll', function(event){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 300,
d = document.getElementsByTagName("kad-header-left");
if (distanceY > shrinkOn) {
d.className += " shrinkedlogoyo";
} else {
d.classList.remove("shrinkedlogoyo");
}
})
}


The script should add "shrinkedlogo" class to the kad-header-left div, which has this css

.shrinkedlogoyo { display: block !important; position: absolute !important; left: 8% !important; top: 2px !important; width: 45px !important; height: 45px !important; }


But, well, this ain't happening and I'm not getting any error. Can you give me a good advice?

Website is http://arthome17.ru

Answer

The script "my-shrinker.js" is not called correctly.

http://arthome17.ru/wp-content/themes/virtue_premium/assets/js/my-shrinker.js?ver=1.0.0

returns a 404.

This is because of get_template_directory_uri() that looking for the script in the parent theme.

Use get_stylesheet_directory_uri() instead with your child theme.

Hope it helps.

EDIT Since the new error in the console (SyntaxError: missing ( before formal parameters)

I will suggest you to use addClass() and removeClass() properties and review you syntax.

RE-EDIT

If you want your script runs on page ready, you'll have to write something like this :

$ = jQuery.noConflict();
$(document).ready(function() { 
    window.addEventListener('scroll', function(event){
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            shrinkOn = 300;
        if (distanceY > shrinkOn) {
            $(".kad-header-left").addClass("shrinkedlogoyo");
        } else {
            $(".kad-header-left").removeClass("shrinkedlogoyo");
        }
    });
});

Add jsfiddle

Here a live example of the working script. Good luck !

Comments