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

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.

Related

A Elements with HREF="#" causing page to reload on click

I have a few a elements which run functions via javascript and have a # set as the href however I have changed something recently that causes these to try and reload the page rather than do nothing and so breaks their functionality.
What can i look for that could cause this?
document.getElementById("link").onclick = function(){alert("do something javascript")};
<a id="link" href="#">Do Some JS</a>
Clicking this however reloads page and am unsure what i have done to cause this to reload the page.
I can't reproduce in the snippet, if i did i wouldn't be asking the question but something is causing these links to reload the page which is not expected behaviour.
So far i can only think or a quick and dirty fix:
$('a[href="#"]')).click(function() {
e.preventDefault();
});
I however would like to know what could be causing this issue to arise.
The problem
Ok i found it thanks for your help:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
location.reload();
}
}
That will do it for sure.
I think it's so that as pages are heavily reliant on ajax there was no way to go back to where you had been.
I figured the easiest way was have the urls update on ajax changes so when i clicked back the url would change to last action and then cause page to reload correctly on pop state change.
My Quick Fix
I will change the code to:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
if(window.location.href.substr(window.location.href.length - 1) != "#") {
location.reload();
}
}
}
This is normal behaviour of a tags if you don't want them to reload your page or scroll to top of your page you should remove href from your a tags. You can also stop them from reloading your page like this:
No reload
No reload
In your function you need to use e.preventDefault() or event.preventDefault(). So for example:
function clickMe(e) {
e.preventDefault();
}
As per the most recent comment, you need to pass in the event to the function so it looks like this:
$('a[href="#"]')).click(function(e) {
e.preventDefault();
});
Note that this is an approach I wouldn't recommend since it will block all links and could cause more problems than intended. You'll want to use a specific class to target your anchors.
try
<a onClick="callback();"></a>
just remove that href= "#"
It will not reload or refresh the browser
try javascript:void(0) instead #
eg.
Link
because without seeing some code we never know what cause this problem.

Javascript onClick confirm not firing

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

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

My website alway scroll up when i click link?

I have a link
Text
when i click this link my page alway scroll up to the top. How do i manage it that when i clik this link my page not scroll up to the top.
Javascript? or something
thank you
you can add some javascript to deny the default behavior.
function myClickHandler(e) {
// your code here
// ...
// new code
if(e.preventDefault){ //firefox,chrome
e.preventDefault();
}
else { // ie
return false;
}
}
if you provide some more detail/example code, we can give you a more specific answer.
Not sure what you are trying to do, but maybe you are thinking of:
<a href="JavaScript:void(0);" >Text</a>
that'll do nothing.
You might want to post an example of a link that does this. My guess is that it's because you don't have an href set for the link or you ended the link href with a "#someId"
It's not that it's scrolling to the top of the page, it's refreshing the page.
An example of a top link:
Some Link
Somewhere <!-- will refresh and you end up at the top -->
EDIT
Ah... Now that you've provided the link... it's the Hash # that's the problem.
To avoid that from happening ( I'm guessing you want to do some Javascript on the link and you're trying to get it to do something.. ) then you need return false; in your javascript. This will return false from the link and won't follow it.
It is because you have only the hash # as "URL". It makes the browser jump to the top of the page (normally it would jump to the element with the corresponding ID if you specify any).
But what is the purpose of such a link if you don't use it?
The [relative] URL # is treated by browsers as the top of the page. Either change the link's href attribute to refer to another resource, or add a click event handler that prevents the default action. Better yet, if you intend it to be a button that triggers a click event, replace the <a> tag with a <button> which is more semantically correct anyway.
<body>
<h1 id="top">First Headline</h1>
<!-- your document here-->
go to Top
</body>
With Javascript you could add some smoothness like slowly scroll up. HTML Links

Categories