Joe Pigott
Joe Pigott

Reputation: 8469

Simple javascript reload not working

Here is the Bin. I am trying to make an example of reloading the page by using location.reload() in the function refresh() and using onclick='refresh()' in a button. For some reason the page is not reloading.

The JS function:

function refresh() {
    location.reload();
}

The HTML button:

<button onclick='refresh()'>Try Refreshing!</button>

Upvotes: 2

Views: 7840

Answers (4)

Tushar Gupta
Tushar Gupta

Reputation: 15933

you can do directly as

<button onclick="window.location.reload()">Try refreshing!</button>

Upvotes: 1

skimberk1
skimberk1

Reputation: 2094

The refresh() function isn't in the global scope. In order to make the function globally accessible, you can do this:

window.refresh = function() {
    location.reload();
};

Upvotes: 2

Barmar
Barmar

Reputation: 782508

Your function is defined inside the

$(document).ready(function () {
    ...
});

body, so the scope of the function name is just that body. As a result, you can't reference it from inline onXXX attributes.

Either associate it with the element using

$("#buttonid").click(refresh);

or define the function outside the document ready function.

Upvotes: 1

NG.
NG.

Reputation: 22914

Your refresh method is not in the global scope - it's enclosed within your document.ready.

Move it out from document.ready into it's own script tag.

<script>
    function refresh() {
        location.reload();
    }
</script>

The edited bin

Upvotes: 5

Related Questions