I’m using this javascript to edit a url to sort a list generated by a none editable plugin in wordpress:
<script type="text/javascript">
var sortRegex = /[sort_by]=w*/;
function priceHighZ() {
location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=price');
}
function priceLowZ() {
location.href = location.href.replace('[sort_order]=DESC', '[sort_order]=ASC').replace(sortRegex, '[sort_by]=price');
}
function dateHighZ() {
location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=date');
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('priceHighZ').addEventListener('click', priceHighZ);
document.getElementById('priceLowZ').addEventListener('click', priceLowZ);
document.getElementById('dateHighZ').addEventListener('click', dateHighZ);
});
</script>
It only works once the page has loaded for the first time, and you reload the page. It doesn’t work on first load.
Is there a problem with DOMContentLoaded, that could cause this to work only once the page is reloaded?
I’ve looked at this but not sure how to apply this example to my code above.
You can use the jQuery .ready() event to be sure that DOM is loaded before execution of the script (like in your link example). But with wordpress you use
jQuery
instead of the alias$
. Using the alias$
with wordpress is possible with for example addingvar $ = jQuery.noConflict();
:You could use jQuery syntax instead of pure javascript replacing for example in:
document.getElementById('dateHighZ')â¦
replacing it by$('#dateHighZ')â¦
.Ensure the Id’s you are binding with click event are not loaded in the DOM in an asynchronous way.
It sounds like that your javascript is running before page is loaded. But when you refresh page is loaded from local and page/element is ready before script. According to MDN:
Give it a chance like this