Forums de discussion

Prevent default on link (invoking prompt)

Jan Tošovský, modifié il y a 8 années.

Prevent default on link (invoking prompt)

Liferay Master Publications: 566 Date d'inscription: 22/07/10 Publications récentes
Dear All,

at the top of article I'd like to insert a link which allows copying article URL to the clipboard.

When utilizing AUI approach, the page is immediately redirected to the target link even with that preventDeafult() directive:

<liferay-ui:icon id="copy-article-link" label="<%= true%>" message="copy-article-link" url="<%= themeDisplay.getPortalURL() + &quot;/c/portal/kb/find_article?resourcePrimKey=&quot; + resourcePrimKey%>" cssClass="icon-paperclip blue" />

<aui:script use="aui-base">
    var copyLink = A.one('#<portlet:namespace />copy-article-link');

    copyLink.on(
        'click',
        function(e) {
            e.preventDefault();
            var textToCopy = copyLink.getAttribute('href');
            window.prompt("Press CTRL+C to copy", textToCopy);
            return false;
        }
    );
</aui:script>


But I accidentally found this non-AUI solution works better as it stays on the page. But it still redirects when any Ok/Cancel button of that prompt is pressed.
<aui:script>
    var copyLink = document.querySelector('#<portlet:namespace />copy-article-link');
    
    copyLink.onclick = function(event) {
        event.preventDefault();
        var textToCopy = copyLink.getAttribute('href');
        window.prompt("Press CTRL+C to copy", textToCopy);
        return false;
    }
</aui:script>

What is the best way to keep the user on the given page?

Thanks, Jan
thumbnail
Travis Cory, modifié il y a 8 années.

RE: Prevent default on link (invoking prompt)

Junior Member Publications: 73 Date d'inscription: 04/06/13 Publications récentes
Hey Jan,

I am sorry for the difficulties. Have you considered using a different approach. Take a look at the tool clipboard.js as an example. Maybe since this is an action you are trying to accomplish, use a button (you can style it like a link) since that is more semantic. From there you can place the url as a data attribute on the button tag. Let me know if that makes sense. Thanks!

-Travis
Jan Tošovský, modifié il y a 8 années.

RE: Prevent default on link (invoking prompt) (Réponse)

Liferay Master Publications: 566 Date d'inscription: 22/07/10 Publications récentes
I found preventDefault must be complemented by event.stopImmediatePropagation();
This combination ensures intended behaviour.