0

I am trying to get my javascript to work in my page, but I have always just put the html on the actual page, but now am wondering if I am supposed to put the <script src before the html as well to make the code work in order to reference the javascript. I have enqueued everything, the js and css from the functions.php Here it is:

<script src='https://artandleatherspencer.local/wp-content/themes/twentythirteen-child/js/myscript.js)

<div id="clockContainer">

<div id="hour"></div>

<div id="minute"></div>

<div id="second"></div>

</div>

here is the code in the functions.php:

function childtheme_parent_styles() {
    wp_enqueue_style('parent', get_template_directory_uri().'/css/style.css' );
    wp_enqueue_style('mytheme_main_style', get_stylesheet_uri());
    wp_register_script('main-js', get_stylesheet_directory_uri() . '/js/main.js');
    if( is_page(507) ) {
        wp_enqueue_script( 'main-js');
    }
}

add_action( 'wp_enqueue_scripts', 'childtheme_parent_styles');

and here the javascript in main.js in js folder

console.log('executing scripts.js');

setInterval(() => {
    d = new Date(); //object of date()
    hr = d.getHours();
    min = d.getMinutes();
    sec = d.getSeconds();
    hr_rotation = 30 * hr + min / 2; //converting current time
    min_rotation = 6 * min;
    sec_rotation = 6 * sec;
 
    hour.style.transform = `rotate(${hr_rotation}deg)`;
    minute.style.transform = `rotate(${min_rotation}deg)`;
    second.style.transform = `rotate(${sec_rotation}deg)`;
}, 1000);

    

css: in style.css file

#clockContainer {
    position: relative;
    margin: auto;
    height: 40vw;
    /*to make the height and width responsive*/
    width: 40vw;
    background: url(clock.png) no-repeat;
    /*setting our background image*/
    background-size: 100%;
}
  
#hour,
#minute,
#second {
    position: absolute;
    background: black;
    border-radius: 10px;
    transform-origin: bottom;
}
  
#hour {
    width: 1.8%;
    height: 25%;
    top: 25%;
    left: 48.85%;
    opacity: 0.8;
}
  
#minute {
    width: 1.6%;
    height: 30%;
    top: 19%;
    left: 48.9%;
    opacity: 0.8;
}
  
#second {
    width: 1%;
    height: 40%;
    top: 9%;
    left: 49.25%;
    opacity: 0.8;
}
1
  • 1
    Your JavaScript code doesn't define what hour, minute, or second are. You need to assign them to elements in the DOM. This is a purely JavaScript issue and best asked at stackoverflow.com, if you're not sure what to do. Sep 21 at 6:29
1

When you enqueue a script with wp_enqueue_script() it adds the <script> tag part for you. If you have HTML that the script interacts with you will need to add that HTML to the page another way. You should not include the script tag in any HTML.

There are many options for adding HTML to a page, depending on where you need it:

Although I'd say that anything other than using a block is becoming obsolete at this point.

Not the answer you're looking for? Browse other questions tagged or ask your own question.