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
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:
Also, make sure jQuery is loaded if you use
$
Here is a version without using jQuery at all:
There are two things you need to understand before adding jQuery code in WordPress.
$
is not a global jQuery variable in WordPressjquery.js
, you will have to use the jQuery keyword to access global jQuery then you can use it as$
if you’re putting jQuery code into
header.php
so make sure you add your<script>...</script>
code afterwp_head();
line so thatjquery.js
could loader first and you could accessjQuery
.So the correct Js code will look like this and you will have to put it after
wp_head();
in the<head>
tag: