For modify the URL without reloading the page we can use:
window.history.pushState('page2', 'Title', '/page2.php');
but if I try it with <a>
element :
<a onClick='my_function()' href='/page2.php'> Click Here </a>
<script>
function my_fnuction(){
window.history.pushState('page2', 'Title', '/page2.php');
}
</script>
It will not work, So how can I use <a>
element and window.history.pushState()
together?
Like twitter and Facebook, user can click on the right button to open the URL in new window, and direct click to get pages and change the URL without reloading
For modify the URL without reloading the page we can use:
window.history.pushState('page2', 'Title', '/page2.php');
but if I try it with <a>
element :
<a onClick='my_function()' href='/page2.php'> Click Here </a>
<script>
function my_fnuction(){
window.history.pushState('page2', 'Title', '/page2.php');
}
</script>
It will not work, So how can I use <a>
element and window.history.pushState()
together?
Like twitter and Facebook, user can click on the right button to open the URL in new window, and direct click to get pages and change the URL without reloading
-
1
onClick='my_function()'
andfunction my_fnuction()
?? – Mi-Creativity Commented Jan 8, 2016 at 7:46
3 Answers
Reset to default 5In onclick you have
my_function
where as the actual function name ismy_fnuction
.You need to cancel the default behaviour, If your onclick function returns false the default browser behaviour is cancelled.
Code:
<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
window.history.pushState('page2', 'Title', '/page2.php');
return false;
}
</script>
add return false;
make it so that href
is not executed, also add return
to your onclick
value:
<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
window.history.pushState('page2', 'Title', '/page2.php');
return false;
}
</script>
solution is also is explained here
Probably just preventing the default behavior of anchor tag. Returning false to the event
<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
window.history.pushState('page2', 'Title', '/page2.php');
return false;
}
</script>
Or using prevent default:
<a onClick='my_function(event); ' href='/page2.php'> Click Here </a>
<script>
function my_function(e){
window.history.pushState('page2', 'Title', '/page2.php');
e.preventDefault();
}
</script>