we have some a link with href made by JavaScript:
stackoverflow uk
how can i provide a direct link like this:
stackoverflow uk
when user disable javascript?
I know there is the tag:
<noscript> stackoverflow uk</noscript>
but then the user will see both the broken link and the correct link. How can i delete the broken link from user interface?
Start with a regular link:
<a id="foo" href="http://example.com">example</a>
Then bind a JavaScript event handler to it:
var link = document.getElementById('foo'); // OR some other means to select the link
link.addEventListener('click', myHandler);
function myHandler(evt) {
// Do whatever else you want to do
// ...
// but don't do the normal link behaviour
evt.preventDefault();
}
Further reading: Progressive Enhancement and Unobtrusive JavaScript
Here's some psuedo code:
text
As you can see it uses the normal link that you want to fall back to by default. When a user has JavaScript enabled, that link never executes as onclick runs first. The return false is to prevent the real link from being triggered.
Related
I'm building a Progressive Web App for iOS and whenever I click on a link, it opens in Safari and not within the app. I'd like to use JavaScript to replace all the Example with JavaScript window.location links so that links open in the app (for example: Example). I would like to avoid the use of jQuery, as it adds extra bloat to my app and I am trying to keep a minimal user experience.
Thanks!
Modifying the DOM (Document Object Model) like that can cause you more problems than get you to the solution you want. I recommend using an event listener and preventDefault.
Here are the relevant docs per those methods:
addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
preventDefault: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Here is a super basic example, your mileage may vary based on whatever framework you're using for your progressive app, consider this more of a starting point rather than a complete solution.
<pre>
Link 1
Link 2
Link 3
Link 4
Link 5
</pre>
<script>
// Array of the anchor (a) elements.
const links = document.getElementsByTagName('a');
// Loop the array
// Yes you can use a foreach or whatever you want instead
for (var i=0;i<links.length;i++) {
// On each of the links add a click event listener
links[i].addEventListener('click', function(event) {
// this in the event is the element, I'm giving assigning it here for clarity
const link = this;
// preventDefault stops the link from being followed
event.preventDefault();
// Set the window.location.href to the link's href attribute.
window.location.href = link.getAttribute('href');
});
}
</script>
I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
To handle swiping I use the script posted here:
http://padilicious.com/code/touchevents/
It works fine.
Now instead of changing the background (what the original script does), I would like it to grab the link contained within an <a> which has a class, and which is normally a link to the next page, but for mouse events like so:
<a href="mypage02.html" target="_self" class="NextP" title="My Second Page">
and then load the page.
I have many pages, with the same structure, I don't want to manually define the links. I want the js to get hold of the current href contained in the <a> and launch it, when triggered by the swipe. If possible.
Thank you ;-)
From what I understand, you want to look for a
<a href="http://example.com/" class="NextP">
element in a page (an <a> anchor tag with a NextP class), and when the user swipes, visit that link.
To do this, I would
look through your HTML for an a.NextP element, and capture its href attribute.
when the user swipes, set window.location.href to this attribute.
window.onload = function(){
var nextPageUrl = document.querySelector('a.NextP').href;
// just guessing how swiping works, I haven't looked through your library
document.body.onswiperight = function(){
window.location.href = nextPageUrl;
};
};
Of course, you would use the correct method of detecting the swipe.
Because this topic turn out to interdisciplinary (but still is about user experience) I'm curiuos what think about this an javacript developers.
My site handling a tags with href starting with # as ajax request. If request was successfully then it's change document hash to appropiate. Now I want to implement action links that call internal js function like going to site top, but I don't want javascript:myAction() reference, because most browsers is showing hint with referencing url when you're over the link. Probably I can use and successfully handle own url schema like action:myAction, but it's not enough solution - user was still hinted about magic url. Another option is using custom attribute like action="myAction" with href as custom string e.g. href="Go to top", but what with browsers compatibility? Last solution is to using a span styled as link to perfom action - user is not hinted about any url, but this is a part of link functionality what suggest that perform an action (going to url default).
What is better and why?
<script>
if(window.addEventListener)//Chrome, Firefox and Safari
document.getElementById('myLink').addEventListener('click',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
else//IE and Opera
document.getElementById('myLink').attachEvent('onclick',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
</script>
Link
You should make your links work first without JavaScript. Then you don't have to worry about someone clicking <a href='/customers'>Customers!</a>. It works nicely and is accessible. Once you've reached this point you put the JavaScript on top to enhance the user experience. How you hook all of these up is up to you - say you want to handle deletes in a generic way, you might have links that look like this:
<a href='/customers/2' class='delete'>Delete customer</a>
<a href='/customers/2' data-action='delete'>Delete customer</a>
Or if it's specific per link, you set the id and wire it up that way:
<a href='/customers/2' id='delete'>Delete customer</a>
All of this wiring up should be done in an external JavaScript file.
I would do this by first writing everything in a way users without JS can use it, like
Go to top
Then I would take JS to enhance it immediatly after the DOM is loaded. First by adding the onclick event, then removing the href, to avoid any link hint (any other content than links probably not pass any validator) and finally a new style attribute that the cursor becomes a pointer on hover.
It is part of the very useful programmatic progressive enhancement structure. This way I get valid and compatible code as well as a comfortable behaviour.
I currently making a filebrowser. If the user clicks on a link to a file a little window open and asks for options (like download and view). I've done this using the onclick attribute. If I click on the link the javascript is executed, but after this the url specified in href opens. What I'm trying to do is: If you click the link javascript get executed and forwards you eventually. But if the link gets rightclicked the "copy link location" should still be available.
I'm thinking of solving this by blocking the forwarding scriptside. So if the link gets rightclicked no javascript is executed and you can copy the link location. But if you left click the link the javascript is executed and the link is not opened.
Is that possible with javascript, or is there any other way of achieving this behavior?
In order to prevent the link executing, one way is to let the "onclick" method return false.
For example:
...
If clickfunc() returns false, a click on the link will not direct to "http://..."
Although you are probably handling it more like
...
<script>
document.getElementById('somebutton').onclick = function() {
...
else { return false; }
};
</script>
You have to prevent default from your click function:
function stopDefAction(evt) {
evt.preventDefault();
}
Yes, you will need to prevent the default action of the event. You can do so by returning false in your onclick attribute.
you can replace href attribute by text "javascript:void(0)", for example:
...
<script>
document.getElementById('somebutton').href="javascript:void(0)"
</script>