Reputation: 83
sorry if this is a basic question but I'm having trouble figuring out how to use a Javascript/jQuery script in my website. (If this is well documented and I just don't know the right terms, please share what to look for - I've had no luck yet online with what I know.)
I'd already designed a site with static pages, it just didn't have a blog. So I put Wordpress in for one of the pages, and figured out how to add in the HTML/CSS design for my existing site's menu using the header.php and footer.php files. However, my jQuery script that's supposed to load when the page is resized in order to change the menu design is not working.
I pasted the <script type="text/javascript" src="jquery.min.js"></script>
code in the <head>
part of the file, adjusted the body tag to <body onresize="myFunction()" <?php body_class(); ?>>
, and added the "myFunction" script to the footer.php file, above the </body>
tag. Above function myFunction() {
I also have window.onload=myFunction();
which isn't working either - so no matter what size the page is loaded at or what size it's changed to the menu is unresponsive.
When I tried adding an enqueue code block to the functions.php file it broke the page entirely, giving a 500 error.
Any advice would be hugely appreciated!
Upvotes: 0
Views: 212
Reputation: 12047
When you add resources such as scrips and style sheets to WordPress you should enqueue them using the functions wp_enqueue_script()
and wp_enqueue_style()
.
Doing this ensures that your scirpt/style is only included once, allows you to declare dependancies, and (in the case of scripts) allows you to add it to the footer should you require/desire.
You can find more information on these functions in the Codex -
In conjunction with these functions, you should use the wp_enqueue_scripts
action, ensuring that your scripts styles get enqueued at the correct time.
So for example, you should place something similar to this in your functions.php file. Because jQuery already exists within WP, you don't even need to specify a location, you just tell WP that you want to enqueue it -
add_action( 'wp_enqueue_scripts', 'my_enqueue_jquery' );
function my_enqueue_jquery(){
wp_enqueue_script( 'jquery' );
}
Upvotes: 1
Reputation: 4605
Check that the path you specify to the jQuery library is correct. In your script tag src="jquery.min.js
is a relative path. This means that the file jquery.min.js
is in the same directory as your html/php/template according to your src
path.
I would recommend using a CDN. You won't have a relative path, need to load your jquery files, and you'll benefit from browser caching if other pages/sites have loaded the same files.
3x
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
2x
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Upvotes: 1