Javascript onClick confirm not firing - javascript

I've placed an onClick goconfirm on a hyperlink per below:
<a href="http://google.com" onclick="goConfirm('This link is to an external site. You are now
leaving mysite.,'href=http://google.com');' target="_blank">Online Account Opening</a>
How do I ensure the confirmation Javascript message fires before sending the user to the new site?
Thanks much for your help and guidance.

You are not preventing the default action in any way. Try this instead:
...
Or if goConfirm is actually a function of yours, you should add return false; to the end of the onclick.
Also fix the mismatched quotes ;)

I guess it was a typo. Try this instead:
Online Account Opening
I also added a return false at the end to ensure the current web page won't be redirected.

You should remove the code to open the new page from the anchor tag to the JS function so that it waits till you confirm.
<script>
function goConfirm(message, url) {
var choice = confirm(message);
if (choice) {
window.open(url, "_blank");
}
}
</script>
Online Account Opening
Fiddle at - http://jsfiddle.net/poonia/2bYKV/

use ... to avoid any change in url

Related

Page reloads when clicking anchor element

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:

Page is Jumping back to Top after targeting the anchor tag

Hello guys im using wordpress and i need to jump to the comments when the user is clicking a link.
The single.php is opening in a new tab and its loading the page on the anchor (comment-id) but after that its always jumping back to the top of the page.
I Know its a problem with javascript (as its working well when i disable js) but im not sure where to find the peace off javascript i have to stop or to change on single.php.
Has anyone an idea how and where to change the javascript. So that i can stay at the comment after clicking the link on a different page?
this is the target <a name="comment'.$comment_ID.'" href="#comment'.$comment_ID.'" onclick="deletco('.$comment_ID.')">DELETE</a>
and this is the link form the other page to the target on single.php
'.$titlecomm.'
thanks for any help
First I encourage you to comment out your JS files one by one it test it out tell you find the responsible js file.
Another approach is, if its javascript issue, then you can do this with jQuery:
$('a.aCommentLinkCssClass').click(function () {
var url = $(this).attr('href').text();
window.location.href = url;
});
and add css class to your link:
'.$titlecomm.'
or if you want just JavaScript only:
<script>
function goToFunction(url) {
window.location.href = url;
}
</script>
and in your html:
<?php echo ''.$titlecomm.''; ?>
try:
onclick="deletco('.$comment_ID.'); return false;"
Or inside the function itself add a return false; at the end. You need to prevent bubbling of the event.

html - How to prevent the browser from opening the link specified in href?

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>

Gmail-style Exit Message

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit

Why does page scroll up when href="#" is clicked?

I have a hyper link as such Link that i have to scroll down the page to get to. This hyperlink is only there to trigger an Ajax request. When ever i click this hyperlink the page scrolls all the way to the top! How can i fix this? I use # because anything else would reload the page. Am I using it wrong?
EDIT:
Its kind of hard for me to explain what am doing so if you run this you get the same problem that i am facing. Even after returning false.
<html>
<head>
</head>
<body>
Link
</body>
</html>
<script type="text/javascript">
document.getElementById("link").onmousedown = function(){
this.style.color="red";
return false;
}
</script>
add a return false; to the event handler assigned:
el.onclick = function() {
// do your code
return false;
}
Or the arguably more elegant way
function(e) {
e = e || window.event;
if ( e.preventDefault ) e.preventDefault()
else e.returnValue = false;
}
Have to tried javascript:void(0) in place of #?
Source:
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
Edit:
Reason:
It prevents the browser from refreshing or navigating to another page.
http://www.tizag.com/javascriptT/javascriptvoid.php
The browser is trying to move to an anchor named #. There isn't any so it scrolls to the very top. To avoid this behavior do what meder mentioned.
you need to stop the event propagation when you click the anchor tag.
The browser is reading the # as an anchor, you ether have a link with an id of "someID" at the top of your page or no ID at all in which case it will just go to the top of the page by default (This seems to be the case for you). You will have to replace the # sign with something to stop this. I'm not sure what would be best, but Evan Mulawski's answer might work. I don't know if this will still allow your ajax code to run properly though.

Categories