Page jumps to the top onclick [duplicate] - javascript

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>

Related

Which call faster href vs onclick

Hi~ i want to calling sequence about anchor tag href property and onclick proerty I have some test
asdfasdf
and click anchor tag. is result show alert and link stackoverflow but
<a onclick="setTimeout(function(){console.log('asdf')})" href="https://stackoverflow.com" >test</a>
this tag first call href proerty! Please explain calling
sequence href and onclick
and if you know another knowledge explain for me Please ToT
So onclick functions actually run before href. This allows you to do a number of really cool things, like stop the link from executing if you want to like so:
function stopLink(event) {
event.preventDefault();
}
click me

I want to attach `onclick` on DOMs using javascript [duplicate]

This question already has answers here:
How to add click event to an element?
(4 answers)
Closed 5 years ago.
Whenever I open a page I am working on, the page makes a lots of amount of doms using javascript, and each one looks like this:
<span class="link img">text</span>
Let me say I assign one of them to a variable called a, for temporary.
I have another function that is to put every of them, including the a, an onclick event, which should be written in the HTML code page, so I can store the whole page and load it later.
The moment it attaches is before loading the doms into document body. Creating doms, and then this function attaches onclick on them, and then load them in the document body.
What it is supposed to do is making this a to:
<span class="link img"
onclick="function(){window.open('http://example.com')}">
text
</span>
So clicking a opens a new window. I made a CSS so every 'link' class looks like a link anyway.
I tried contain one of these into the function to achieve the above change:
a.onclick = function(){window.open('http://example.com')};
,
a["onclick"] = function(){window.open('http://example.com')};
,
const openFunc = function(){
window.open('http://example.com')
};
a["onclick"] = openFunc;
I don't know why, they don't attach onclick property on a.
I didn't understand what you are saying but if you want to add a event on variable 'a' which have the object reference of an element:
Use a event listener
a.addEventListener("click",funcNametocall,false);
read about it here
http://www.w3schools.com/js/js_htmldom_eventlistener.asp
Thomas' reply made me look back at the anchor tag once more time, and it awkwardly solved the problem.
Here's what I put in the function that is to make every one of the doms to a link one:
actually changed 'span' tag to 'a' tag.
I could use a['href'] = 'http://example.com'; to add the link to the tags, or doms, and leave it in HTML code.
Hello Put these code in your head section
<script type="text/javascript">
function openWindows(argument) {
window.open('http://example.com')
}
</script>
and replace your span tag with the following code...
<span class="link img" onClick="openWindows();">text</span>
May check this code and it work, I hope this will also help you.

avoid change location in anchor (html) [duplicate]

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.

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();
});

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