skip to Main Content

Good day,

I am having a problem with reloading page when anchor link is clicked #about-us in wordpress site. If I hard code the link in wordpress header.php the page is reloading on anchor click e.g. <a href="<?php echo get_site_url(); ?>#about-us" onClick="window.location.reload(true);">About us

But my problem comes when I want to use the link in wordpress menu, the page is not reloading on anchor click and I would like the page to load on anchor click. I have tried to add a javascript code into header.php but still the page doesn’t refresh. JS code below:

<script>
$("#menu-item-2").on("click", function(e){ 
  e.preventDefault();
  window.location.reload(true)
});

Please assist, Thank you in advance for your help.

2

Answers


  1. If your javascript is running before the node exists, it won’t find the node thus won’t bind to the click event.
    Try wrapping your code into a load listener:

    <script>
    window.addEventListener('load', () => {
      $("#menu-item-2").on('click', function(e) { 
        e.preventDefault();
        window.location.reload(true);
      });
    });
    </script>
    

    Also, make sure jQuery is loaded if you use $

    Here is a version without using jQuery at all:

    <script>
    window.addEventListener('load', () => {
      document.getElementById('menu-item-2').addEventListener('click', function(e) { 
        e.preventDefault();
        window.location.reload(true);
      });
    });
    </script>
    
    Login or Signup to reply.
  2. There are two things you need to understand before adding jQuery code in WordPress.

    1. $ is not a global jQuery variable in WordPress jquery.js, you will have to use the jQuery keyword to access global jQuery then you can use it as $

    2. if you’re putting jQuery code into header.php so make sure you add your <script>...</script> code after wp_head(); line so that jquery.js could loader first and you could access jQuery.

    So the correct Js code will look like this and you will have to put it after wp_head(); in the <head> tag:

    jQuery(function ($) {
        $("#menu-item-2").on("click", function (e) {
            e.preventDefault();
            window.location.reload(true);
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search