Search code examples
htmlsapui5

How can I navigate using anchor tag in SAPUI5?


I know how to do using html and JavaScript

<h2 id="C4">Chapter 4</h2>
<a href="#C4">Jump to Chapter 4</a>

This is what I am trying in SAPUI5. On click to Back to top link it should navigate to helpButton. This is not working for me.

<Button id="helpButton" icon ="sap-icon://sys-help" />
<Link text="Back to top"
      press="#helpButton"/>

Solution

  • You can actually do this in UI5. A little differently than how you tried though.

    The problem is that the UI5 ID is not the same as the HTML ID (which is what you want to use with the hash-link for the browser to jump there). Also, you cannot specify a URL inside the press "attribute" of the link. The press "attribute" is in fact an event (so you can only specify an event handler name).

    So to be able to do what you want, you have to use the href property of the Link and fill it with the HTML ID of the target control. You can do this on the onAfterRendering hook of the view (that's when you are able to find the HTML ID of the target control):

    onAfterRendering: function() {
        var oRef = this.byId("target").getDomRef();
        this.byId("link").setHref("#" + oRef.id);
    }
    

    You can find a working fiddle here: https://jsfiddle.net/93mx0yvt/26/.