Archived topic
Can't add custom js to gp child theme
6 replies · Started by Bruno on February 18, 2018
Trying to add js to content for testing, simple hide and show jquery.
I can do this with underscore and twentyseventeen but can't do it with generatepress child...
Here is the setup:
/js/a.js
/* Compatibility Mode */
jQuery('h1').on('click', function() {
jQuery('h2').hide();
})
And then in functions.php (C:\+Data-Nov-2017\x_a_m_p_p\htdocs\wp-sandbox\wp-content\themes\generatepress_child\functions.php)
function a() {
wp_enqueue_script( 'a', get_template_directory_uri() . '/js/a.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'a' );
Why isn't it working with GP?
get_template_directory_uri() points to the parent theme.
You need to use get_stylesheet_directory_uri().
Ah ok, didn't know linking to child theme required different code!
Thanks Tom;)
New problem!
I installed this plugin:
Scripts n Styles, https://wordpress.org/plugins/scripts-n-styles/
I added this code on this section of the plugin ,
Scripts
(end of the body tag):
/* Compatibility Mode */
jQuery('h3').on('click', function() {
jQuery('h4').hide();
})
Now this works with all other themes, but not with generate press child theme, I must be doing something wrong again?
GP doesn't load jQuery by default.
You can add it like this:
add_action( 'wp_enqueue_scripts', 'tu_load_jquery' );
function tu_load_jquery() {
wp_enqueue_script( 'jquery' );
}
Hi Tom,
I just can't get this working for some reason...
Can you please tell me exactly what code to put where to get this script going?
What I'm trying to do is implement this: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_val_get
This is what I have done:
HTML:
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
<button>Show Value</button>
JS:
jquery("button").click(function(){
alert("Value: " + jquery("#test").val());
});
});
JS file name in directory:
C:\+Data-Nov-2017\x_a_m_p_p\htdocs\wp-sandbox\wp-content\themes\generatepress_child\js\localandcdn.js
CDN link required:
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
My code in functions.php
// Link to Jquery CDN form Tom at generate press
function localandcdn() {
if ( is_single( 'localandcdn' ) )
wp_enqueue_script( 'localandcdn', get_stylesheet_directory_uri() . '/js/localandcdn.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'localandcdn' );
add_action( 'wp_enqueue_scripts', 'tu_load_jquery' );
function tu_load_jquery() {
wp_enqueue_script( 'jquery' );
}
Additionally, here is it on codepen:
First, I wouldn't apply it to all button elements. Give your button a class:
<button class="my-button">Button</button>
Then add this into the wp_footer hook in GP Hooks:
<script>
jQuery( document ).ready( function($) {
$( 'button.my-button' ).on( 'click', function(e) {
alert("Value: " + $("#test").val());
} );
} );
</script>