I’m trying to enqeue a custom.js in my wordpress theme created from scratch. Here’s what I have;
Here’s what I have tried
functions.php
<?php
function add_theme_scripts() {
wp_enqueue_style('default-style', get_stylesheet_directory_uri() .'/style.css');
wp_enqueue_style('bootstrap-style', get_stylesheet_directory_uri() .'/css/bootstrap.min.css');
// Dequeue WordPress included jQuery
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri() . '/js/jquery.min.js', array(), '3.0.0', true);
wp_enqueue_script('bootstrap-script', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '1.0', true);
wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
custom.js
document.addEventListener('DOMContentLoaded', function () {
const colorButton = document.getElementById('color-button');
const colorDisplay = document.getElementById('color-display');
const colors = ['color1', 'color2', 'color3', 'color4', 'color5'];
let currentIndex = 0;
function changeBackgroundColor() {
document.body.className = colors[currentIndex];
colorDisplay.textContent = getComputedStyle(document.body).backgroundColor;
currentIndex = (currentIndex + 1) % colors.length;
}
colorButton.addEventListener('click', changeBackgroundColor);
});
Have tried to deqeue the built in jquery and enqeued the latest. Have tried the register and then enqeue variant as well but it just wont list out the javascripts when I look in the source code.
Have tried a simple variant where I just have
<?php
function add_theme_scripts() {
wp_enqueue_style('default-style', get_stylesheet_directory_uri() .'/style.css');
wp_enqueue_style('bootstrap-style', get_stylesheet_directory_uri() .'/css/bootstrap.min.css');
wp_enqueue_script('bootstrap-script', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '1.0', true);
wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
The styles are there, the js wont show. What am I missing? It’s a simple script that should change the background color on body when one click a button.
2
Answers
Finally got it to work with
and then
Try unrooting your js in
`
`