# How to use api.onPageChange with api.createWidget?

**URL:** https://meta.discourse.org/t/how-to-use-api-onpagechange-with-api-createwidget/242744
**Category:** Development
**Tags:** ember
**Created:** [October 24, 2022, 2:55am UTC](https://meta.discourse.org/t/how-to-use-api-onpagechange-with-api-createwidget/242744 "2022-10-24T02:55:24Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![rahim123](https://avatars.discourse-cdn.com/v4/letter/r/df705f/32.png) [@rahim123](https://meta.discourse.org/u/rahim123)
#### Post date: [October 25, 2022, 3:52pm UTC](https://meta.discourse.org/t/how-to-use-api-onpagechange-with-api-createwidget/242744/2 "2022-10-25T15:52:36Z")

</div>

This is my more proper attempt. When I run it without the `api.onPageChange(()` function it works, but doesn’t randomize the image until I do a hard page refresh. When I add the `api.onPageChange(()` function it doesn’t show any image at all. Any tips on what I’m doing wrong?

```plaintext
<script type="text/discourse-plugin" version="0.8">

api.onPageChange(() => {
        doStuff();
});

function doStuff() {

const h = require("virtual-dom").h;

let banners = new Array();
banners[0]="https://example.com/uploads/default/original/1X/9d9762a4129c78c478d14ff857c3bd1f2be0322a.jpg";
banners[1]="https://example.com/uploads/default/original/1X/04ede2abd9ac117c64988a5b0bcf033474381527.jpg";

let GoTo = new Array();
GoTo[0]="https://google.com";
GoTo[1]="https://brave.com";

let Number = Math.round(1 * Math.random());
let TheLink = GoTo[Number];
let TheImage = banners[Number];

  api.createWidget("top-banner-widget", {
    tagName: "div.top-banner",
    html() {
    return h("div#top-banner", [
      h(
        "a.custom-ad-link",
        { href: TheLink },
        h("img", { src: TheImage})
      )
    ]);
    }
  });
}
</script>

<script type="text/x-handlebars" data-template-name="/connectors/above-main-container/inject-widget">
  {{mount-widget widget="top-banner-widget"}}
</script>
```

---

_[View the full topic](https://meta.discourse.org/t/how-to-use-api-onpagechange-with-api-createwidget/242744)._
