N
N
N!crO2018-02-05 16:51:16
JavaScript
N!crO, 2018-02-05 16:51:16

How to write or include a js file in wordpress?

There is a js file for working with certain DOM elements, but when you go to another page of the site, and these elements are not there, the script crashes. How to write or connect a script correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Vorotnev, 2018-02-05
@n1croo

from discussion:

var slides = document.querySelectorAll('.slider-item');
var sliderToggles = document.querySelectorAll('.slider-toggle');
var currentSlide = 0;

if ( slides.length > 0 ) {
    var slideInterval = setInterval(nextSlide, 2500);
}

function nextSlide() {
    sliderToggles[currentSlide].classList.remove('slider-toggle--active');
    slides[currentSlide].classList.remove('active');
    currentSlide = (currentSlide+1)%slides.length;
    sliderToggles[currentSlide].classList.add('slider-toggle--active');
    slides[currentSlide].classList.add('active');
}

The problem was that the slider was launched without checking if there were any slides at all. Accordingly, if they were not on other pages, then everything broke.

Q
Qleager, 2018-02-05
@Qleager

functions.php

function mytheme_scripts_styles() {
  
  wp_enqueue_style( 'mytheme-style', get_stylesheet_uri(), array(), '1.0.0' );
  wp_enqueue_script( 'mytheme-script', get_template_directory_uri() . '/scripts.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts_styles' );

Include style.css and scripts.js in the theme folder
Must be written before the closing body tag , it is standard in footer.php . Responsible for the output of scripts .
This is before the closing head . Responsible for rendering styles

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question