0

I wrote the following function and put it between script tags in the header of my wordpress website.

function turnShopBlue(){
    var location = window.location.href;
    if(location === "MY URL GOES HERE"){
        var menuItem = document.getElementById("menu-item-3352");
        menuItem.classList.add("current-menu-item");
        //document.querySelector("#menu-item-3352").addClass("current-menu-item");
    }
}
turnShopBlue();

But for some reason the function doesn't run. Each time I go the URL (page) that I choose in "MY URL GOES HERE", the class current-menu-item doesn't get added. What do I miss?

I've already tried with triple === and double ==, without success.

EDIT SOLUTION:

My mistake was that I placed the script in the header, the problem here is that the script then runs before the entire DOM is rendered. So alot of the variables I instantiate don't have the good values. The problem was solved by loading the script in the header;

Also, I had to put it in a jQuery document ready function to autoload it on pageload.

Arne De Belser
  • 111
  • 3
  • 12
  • Place the script in the footer.php file. – jeff Feb 08 '18 at 22:04
  • 3
    It might be that the DOM element has not been loaded when you try to add the class. Try putting the script tag before the end of the body. – zfrisch Feb 08 '18 at 22:05

1 Answers1

2

Always put your Javascript code at the end (footer) of your body tag. This way, all your HTML will be parsed before any Javascript execution, further, your external scripts must be placed there as well to improve page's loading performance.

<html>

<body>
  <tag-name id='menu-item-3352'></tag-name>

  <script>
    function turnShopBlue() {
      var location = window.location.href;
      if (location === "MY URL GOES HERE") {
        var menuItem = document.getElementById("menu-item-3352");
        menuItem.classList.add("current-menu-item");
        //document.querySelector("#menu-item-3352").addClass("current-menu-item");
      }
    }

    turnShopBlue();
  </script>

  <script external Javascript resources></script>
  <script external Javascript resources></script>
</body>

</html>

Resource

$(document).ready equivalent without jQuery

Ele
  • 31,191
  • 6
  • 31
  • 67