Reputation: 10567
I have included jquery directly from CDN like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
.
I have included my javascript
file in the footer like
<script type="text/javascript" src="<?php echo get_template_directory_uri();?>/javascript/tsblog.js"></script>
my javascript code is
jQuery( document ).ready(function($) {
console.log( "ready!" );
$("#start-reading").click(function() {
console.log("click");
});
});
One simple jQuery click function. Here in the console i can see the ready
message. but on clicking the element with id start-reading
nothing is happening.
Here is the markup
<button id="start-reading">
</button>
I'm new to wordpress , is there something wordpress realted which i'm doing wrong ? Because this is supposed to work in non-wordpress environment.
Upvotes: 1
Views: 5728
Reputation: 1763
Use wp_enqueue_script as follows and I figured the last argument which flags for in footer print as mandatory. Last argument makes difference.
wp_enqueue_script( 'custom_script_unique_handle_name', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '', true );
Upvotes: 0
Reputation: 847
If it is a dynamically added button (e.g. during the execution of some code), you can use onclcick
in the HTML code of the button.
jQuery('#parent')
.html('<button onclick="test_func()">Test</button>');
BUT the declaration of the target function ( test_func()
) must be in the root of the file (not function in function)
Upvotes: 0
Reputation: 842
Keep use jQuery
instead of $
. Just like the below code.
jQuery(document).ready(function() {
console.log( "ready!" );
jQuery("#start-reading").click(function() {
console.log("click");
});
});
Check your element ID whether it's #start-reading
Or #start_reading
.
Upvotes: 1
Reputation: 90148
WP makes sure it only loads scripts once. So it collects all script requests from all plugins and decides the correct order based on dependencies and priority.
To correctly add your script in WordPress you need to use wp_enqueue_script().
Upvotes: 1
Reputation: 521
Use the recommended way, add these code to functions.php
function your_theme_scripts() {
wp_enqueue_script( 'your-theme-script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'your_theme_scripts' );
jQuery is already integrated to WordPress, now you can wirte jQuery code to the script.js file.
Upvotes: 0