avoid change location in anchor (html) [duplicate] - javascript

This question already has answers here:
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
(56 answers)
Closed 9 years ago.
I am thinking about the best solution handling click events avoiding the change of the location in the browser(#).
These are the two scenarios:
1. <a class="someclass" href="#">Click me</a>
(This is ok, but adds a "#" in the url)
2. <a class="someclass" href="javascript:void(0)">Click me</a>
(Seems to be better, the url never changes, but I don't know about compatibility in all browsers, or even when javascript is disabled)
Which one is the best solution ?

The href parameter isn't a requirement as far as I know. Just remove it and still hook up the events you need.

In first method..Just add return false where you are handling the click event. Then it wont add # to URL

use Javascript:void(0);.
The void operator was pretty much to only way force the click to do nothing.

You should use href="javascript:void(0)" in adjacent with onClick because it will prevent the browser from loading a new page.if you want to use onCLick for the hyperlink and require the client to not be direct to a new page after clicking on the hyperlink, return void(0) following href='javascript:void(0)' will prevent that to happen.

Related

How can I specify an anchor tag behaves like a hyperlink, without an href and without an anchor name?

Okay so this one has some similar threads but I couldn't find anything that nailed it on the head, so here we go.
I'm trying to simulate a link using the anchor tag, like so:
<a onClick="javascript: DownloadPorn();">Click Here!</a>
All of this works fine and dandy; the link shows, I can click it, and my javascript method is successfully executed.
The question here, is how can I correctly force the link to display in the 'same manner' as an actual 'HTML Link'? Or rather, in the 'same manner' as if I were to have an href in the above mentioned tag; like so:
Click Here!
Now... THIS Code snippet forces the link to display in the manner that I expect it to, but in using this method, when a link is clicked, the scroll location is bounced back to the top.
It's probably clear, that this is not an intended behavior for the framework I am trying to develop. If anyone has any suggestions to overcome this particular issue, I would greatly appreciate your input.
--- While typing this all up, I considered that I could place a static anchor at the top of the screen( say 0,0 or -,- ), and force all of my links to reference that anchor. If anyone sees any viability in this solution, I'm likely to explore it.
--- Edited ---
Accepted Answer:
In order to have an anchor behave as a hyperlink, without manipulating the browsers current position; utilize a Javascript method returning nothing(?) in the href attribute, or a valid return of 'false' in one of the alternate event handlers for an anchor, I.E. the onClick method.
Possible solutions:
Link
Link
Link
Thanks again, everyone.
--- End Edit ---
If you use return false at the end of your onclick attribute it will not make it scroll anywhere.
Click Here!
or you can make your function return false, and return its result (false) as well as execute it in the onclick attribute, which is shorter:
<script type="text/javascript">
function someFunc() {
// all your function code here
return false;
}
</script>
Click Here!
Set the javascript function to the href.
Click Here!
Edit: Just to note some consider this bad practice.
Set the href to javascript:void(0);, this will mean the browser displays the link as if it had a real href:
Click Here!
There are other methods such as setting the href to #, but the advantage of the one shown is that you don't have to worry about returning false or specifying return DownloadBooks().
This question has some good info about the use of javascript:void(0).

What does href expression do?

I have seen the following href used in webpages from time to time. However, I don't understand what this is trying to do or the technique. Can someone elaborate please?
An <a> element is invalid HTML unless it has either an href or name attribute.
If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.
Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.
He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.
Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).
There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.
basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)
<script>
function doSomething() {
alert("hello")
}
</script>
click me
clicking the link will fire the alert.
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Avoids the "moving to the top" effect of the empty href="#"
Avoids the use of javascript
Drawbacks:
You must be sure the anchor name is not used in the document.
The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.
Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.
is just shorthand for:
It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.
Interesting fact
I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).
It is a way of running Javascript instead of following a link:
link
When there isn't actually javascript to run (like your example) it does nothing.
Refer to this:
Link to the website opened in different tab
Link to the div in the page(look at the chaneged url)
Nothing happens if there is no javaScript to render
javascript: tells the browser going to write javascript code
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id) works as onClick but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
Since it is a styling issue, instead of polluting the HTML with non valid syntax, you could/should use a W3 valid workaround:
Format the HTML properly, without href, following the W3 accessibility guide lines for buttons.
Use CSS to fix the initial goal of applying a clickable UX effect on a control.
Here's a live example for you to try the UX.
HTML
<a role="button" aria-pressed="false">Underlined + Pointer</a>
<a role="button" aria-pressed="false" class="btn">Pointer</a>
CSS
a[role="button"]:not([href]):not(.btn) { text-decoration: underline; }
a[role="button"]:not([href]) { cursor: pointer; }
I was searching for a solution that does not refresh pages but opens menu items on Ipads and phones.
I tried it on also mobile, It works well
Dr
1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows
<div class="table-cell">
<span id="clearRow{id}">
Clear
</span>
</div>
<div class="table-cell">
<span id="deleteRow{id}">
Delete
</span>
</div>
//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
});
//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
//depending upon levels of parent / child use 1 to many .parent().parent().parent()
$(this).parent().remove();
});

A href pointed to nowhere added # to url

I have a href which pointed to #
<a href="#" id="bla" >Bla<a>
I have onclick function which displaying popup on click on that a href.
function doingClick()
{
//display popup
return false;
}
But after click symbol # every time added to the url in browser.
So for example if url was like that before I click on my link http://mywebsite.com
But after click on a href the url looking like that: http://mywebsite.com#
Is there any way to avoid such behavior?
To avoid this try adding return false;
Link
You could also use void(0)
Link
There's a popular question related to this (small religious war!) at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
Link
Do not forget to return the return of your function. Otherwise you will just call it without suspending the subsequent events.
While there are other valid solutions, I personally prefer this shorter solution.
Link
Another benefit is that this solution does not scroll to the top of the window.
So i think the better way of doing this is to remove href from a element
<a id="bla" class="href" >Bla</a>
and than to make it looks like a href just add simple css class
.href
{
color: #2289b8; //color of the link
cursor: pointer;
}
This idea comes to me when i looked in to source of SO add comment button
Instead of adding a href, you could add a style="cursor:pointer;"
this has the same effect of displaying it like a hyperlink, without the in-page anchor effect.
<a id="bla" onclick="return doingClick()" style="cursor:pointer;">Link</a>
The url is not pointed to nowhere. The URL is a relative URL to # in other words the URL resolves to <current_url># which in this case is http://mywebsite.com#.
To avoid this behaviour, you have to change the URL.
If you have a onclick-handler that returns false, then that should prevent the link being active :
link
You can also use javascript:void(0) as the link href.
In either case, be mindful of the decreased accessibility of your site when you use javascript to access some parts of it. Those users that have javascript disabled, doesn't have javascript enabled browsers or use a screenreader or other accessibilty tools may not be able to use the site.
If you don't get better answer, you could make nasty ugly workaround by placing script tag very early on page (on the beginning of body or in head) with following javascript:
if(document.location.href[document.location.href.length-1]=='#'){
document.location.href = document.location.href.substring(0, document.location.href.length-2)
}
I DO NOT RECOMMEND you to do this as will cause double requests to server when # is in url, but it is here if you have to.
The # is used for linking the element ID's, and will always be added to your URL when used in "empty" hrefs. What you could do, if it REALLY annoys you, is to remove it from location.href in your doingClick function
A simple workaround would be set the href empty:
<a href="" id="bla" onClick="alert('Hi');">Bla<a>
Which still works.
If you want to keep the "events" that happens in href="#"
You can simply leave it empty: href=""

Page jumps to the top onclick [duplicate]

This question already has answers here:
Prevent href="#" link from changing the URL hash
(11 answers)
Closed 8 years ago.
I have a click in the middle of a website with code like <a href=“#“ onclick=“…
The function works well, but the a href=“#“ let’s the page always jump to the top when I click on the link. Is there any way around it?
Thanks
Just add ; return false; to the end of your onclick, for example:
<a href="#" onclick="alert('hello'); return false;">
Edit: Hemlock's answer is a good alternative, but yet another one is a combination of the two:
<a href="javascript:void(0)" onclick="alert('hello')">
The advantage of this is that you're explicitly saying that the <a> should do nothing with the href, and the onclick event handler is a separate attribute. If you later decide to attach the onclick handler using JavaScript rather than inlining it (recommended), it's simply a matter of removing the onclick attribute.
Alternate method
Put the javascript in the href and make sure the code ends in a call to void
add
return false;
at the end of the onclick statement
that is
Click Here
if you want an element that does some javascript onclick, you should not use the a tag. The a tag is for navigation from one page to another. You should use span and then you don't have to provide a href attribute. The problem lies in the fact that you chose the wrong HTML element for your case.
<span onclick=""></span>

Why href="#" is High Priority than onclick

I usualy found the following code:
click
but sometime my browser go to the top of the page?
Why href="#" is High Priority than onclick?
It isn't higher priority. The onclick fires and then the browser follows the link.
If you don't return false (note spelling) or func throws an error (thus not reaching the return statement) the event won't be canceled.
(As fallbacks for if the JS fails or is disabled go, however, a link to the top of the page is really sucky. Progressive enhancement is the way forward.)
If the only reason you want to have a href value is to enable the hand cursor, you can use css style instead:
<a style="cursor:pointer;" onclick="func();return false">click</a>
...and a decade later, here's the answer to the question asked above;
click
To save confusion, this answer does not address the "return false" aspect. That subject can be researched separately.
PS; Technically there is no hierarchy (AKA "priority") for what happens when an Anchor Tag is clicked. But since HREF is the "default" action /
event for an anchor tag, from a certain perspective, HREF does "take priority" over OnClick.

Categories