Relative URL to a different port number in a hyperlink?
To redirect to a different port while retaining the domain, use a relative protocol URL: simply prepend the new port with :
after //
. This is a neat example:
This code keeps the current protocol and domain, and only alter the port to 8080
. This is very handy for moving between services on the same domain but residing on different ports.
Manipulate port number using JavaScript
For a living, breathing and dynamic web experience, often you need a flexible solution. Using JavaScript to construct URLs, port numbers can be altered onthefly. Here it is:
This crafty script listens for the click event on hyperlinks, overrules default behavior, and redirects the user to the URL built from endpoint's hostname and path, but coupled with a different port number.
Optimize user experience
When you decide to maneuver URLs with JavaScript, always care about user experience:
- Transparent Change: It's like a magician showing the trick before it happens - show the revised URL when users hover over a link or do a right-click to copy the link address.
- Seamless Switch: Give a smoother transition to users, apply changes after the page has loaded.
- Cross-browser Compatibility: Make sure the magic trick works on every table. Verify your magic trick across multiple web browsers for uniform experience.
Navigating without heavy scripting
For maintaining high accessibility and user experience, URL construction should not heavily rely on JavaScript, Knight of Coding:
- On Initial Load: Ideally, the links should be perfect when the page first loads. JavaScript could then be used as an enhancement, not a mere constructor.
- Progressive Enhancement: Even when JavaScript is turned off or fails, the user should still be capable of navigating the site, although on their default ports.
Get hands dirty with code
There are various scenarios that may arise, and understanding them with code examples can help you better navigate the situation:
- Hover and Change Ports: Attach
mouseover
event to modify href attribute such that users see the amended port number on hover. - Event Handling Delegate: Assign the listening of events to a common parent instead of attaching handlers to each link which provides efficient performance.
- Absolute vs Relative Links: A function that discerns between a link being absolute or relative and builds the URL accordingly.
- Special Characters: Ensure any peculiar characters in URL paths are encoded to evade any transmission issues.
Was this article helpful?