Scenario
It might happen that on a certain event you want to reload or refresh a page. The events over which you may want to trigger page reload are click of a button, click of a link, selection of a checkbox.
To reload or refresh a page, reload()
function of javascript location
object is used. Syntax is :
location.reload()
Suppose there is a button on whose click the page needs to be refreshed. Basically, you need to call the above line of code on click of a button. This can be done in two ways :
- Using
onclick
attribute of button. This method is purely based on javascript and does not require jQuery. - Calling a jQuery click event handler for this button.
Following code demonstrates both these approaches.
<html> <body> <!-- Approach 1 : refresh by onclick handler --> <button onclick="location.reload();">Refresh by onclick attribute </button> <!-- Approach 2 : refresh by calling an event handler function --> <button id="loader">Refresh using event handler</button> <script type="text/javascript"> <!-- bind click event handler to button with id as "loader" --> $("#loader").click(function(){ location.reload(); }); </script> </body> </html>
Both the approaches do the same task but in different ways.
Let’s tweak in :
location
is a property ofwindow
object.window
object represents the current open window.location
object has all information about the current url. You can use it easily obtain parameters such as the url of current page, its host, port, protocol etc.- The
reload()
function takes an optionaltrue
orfalse
parameter. When set to true, it fetches the page from the server rather than the browser cache. The parameter defaults tofalse
, so by default the page may reload from the browser’s cache. reload()
function does not ask a user for confirmation of page refresh. It just refreshes it.