'OnClick' interrupts my hyperlink - javascript

I have an <a> tag that contains a span. The span has javascript attached to it that does something. As a result, when the span is clicked, the javascript runs, but the <a href> is ignored and it doesn't navigate to it.
Is there a way to make it continue to navigate as normal?
<a href='http://www.google.com'><span>some text</span></a>
the click event is actually registered some other way than onclick, my question title is a bit misleading.
Hovering over the link puts the URL into the status bar as you'd expect, just clicking it does nothing.
The javascript is simple return true; at the moment while I try to figure it out.
I suspect as the javascript is in the span and not the a that it gets confused about how to propogate back up to the href once the javascript is done.
I'm afraid I don't know how it's bound, because it's some bizarre third party component.

I suspect as the javascript is in the span and not the a that it gets confused about how to propogate back up to the href once the javascript is done.
Yes. If your onClick handler is on the span, the browser can't read the hyperlink's href attribute. If the link has an id, you can do :
function onclick()
{
//Do your things...
var link = document.getElementbyId('your_link_id').href;
window.location.href = link;
return true;
}

Your javascript is probably returning a value that is non-true (a value that evaluates to boolean false). The simple solution is to add a return true statement to the end of the function/code that runs when the link is clicked.

If you're using jQuery, make sure you don't return false in your event handler. That will override the defaults.
If not: you may need to explicitly code what you want your link to do after your JS:
click here
This will execute a function, then redirect the window to the proper location.

Related

how to stop refreshing parent page while child window open?

when i click link to open child window, parent page refresh automatically. how can i stop it?
parent page should not refresh while open child window. how to do this? please help me.
my code is as below given:
<html>
<head>
<title>login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var popup;
function ShowPopup(url) {
if(popup)
{
popup.close();
}
popup = window.open(url, "self", "toolbar=no,scrollbars=yes,location=no,statusbar=no,menubar=no,resizable=0,width=300,height=350,left = 0,top = 0");
popup.focus();
}
</script>
</head>
<body>
Sign In / Register
</body>
</html>
Your page refreshes because not only is your function called, but also the
hyperlink indicated by the a tag is executed. So you have two things happening
at the same time:
the hyperlink itself navigates to whatever is in the href attribute,
even if it is empty. If href is empty it means: reload this page.
the onclick event handler also does something (opening a popup), but it
does currently not cancel the first effect.
In a first reaction one might just remove the offending href
attribute. This solves the problem, but introduces another: you lose all the nice
styling on the displayed hyperlink text (like underline, color, changing cursor, tab order, ...),
which is generally not what you want.
Here are some more convenient solutions:
Let the onclick event handler return false
Returning false will cancel the anchor's default behaviour and the content of the href attribute will be ignored:
onclick="ShowPopup('popup_login.asp'); return false;"
If you care about browsers that have no javascript support (or have it disabled), then put
a meaningful fall-back url in the href attribute, like:
href="javascript_is_required.html"
Use event.preventDefault
This is an alternative to return false. It has the advantage that you can make it
execute as the first instruction, so that if a run-time error occurs in the other code
it will already have done it's job:
onclick="event.preventDefault();ShowPopup('popup_login.asp');"
Note that this event object is defined by all browsers in the context of event attributes,
and is to be distinguished from the window.event object, which is not supported by
all browsers.
Use hash notation in href
Give the anchor a name
and then reference that name in the href attribute. This way
the anchor will navigate itself into view, which
it usually already is when the user clicked it:
name="loginlink" href="#loginlink"
You will often see the shorter variation href="#", but this will scroll the page to the top
when clicked, which might be OK if you know for sure the page is not scrolled down.
Still, the use of "#" has a side-effect: when clicked the url changes and the
previous url is put on the browser's history stack. So if after clicking the link you press the back button,
you stay on the page. This may be undesired.
Use the javascript: protocol to do nothing
href="javascript:"
This will make the hyperlink execute any javascript following the colon, and since there
is none there, nothing will happen. The browser history is not modified. There are variations
to this method, like javascript: return false; or javascript: void(0);
Use the javascript: protocol to handle the click event
With this solution you no longer use the onclick attribute. Instead you move the code
to the href attribute:
href="javascript: ShowPopup('popup_login.asp');"
Separation of lay-out and code
The original code and all the above solutions still have an issue that many developers
do not like: HTML is mixed with javascript code. It is better to separate these two.
This can be done as follows:
<a href="javascript_is_required.html" id="loginLink"
title="Click here to log on"> ... </a>
...
<script>
document.getElementById('mylink').onclick = function(e) {
e = e || event; // cross-browser way to get event object
e.preventDefault(); // cancel the default click behaviour
ShowPopup('popup_login.asp'); // your custom code comes here
return false; // cancel the default click behaviour
};
</script>
A few will say this also
has a down-side: it is harder to identify the code that executes on a click.
The above code will attach the event handler to the click event of the mylink
element. Make sure to have it execute only after the document has loaded.
The event handler cancels the default click
behaviour in two ways. Choose the one you prefer, or both if you want. As it is
cancelled, the navigation to the href attribute value is never executed. The first
line deals with browser specifics as older IE browsers do not pass the event object
as an argument to the event handler, but expose a global event object instead.
If you don't have to support pre-IE9 browsers, you can improve more by using
addEventListener('click', myfunction); instead of onclick = myfunction; in the
above code. This has many advantages: more event handlers can be attached to the same
event, and you can also remove them one by one. jQuery offers good cross browser support
for this with .on().
There are several variations on the above solutions, all with their
benefits and downsides. You could even step away from using an anchor for this purpose
and use another element instead with styling added to it.
Write return false(); after the window.open() JS method.
In case the above snippet is not working, change the default <button> tag to normal <input> tag with type="button". This will solve the problem.
Below is the code snippet:
JavaScript
<script>
function tagedlist() {
window.open("http://w3schools.com","mywindow","menubar=1,resizable=1,width=1000,height=1000");
return false;
}
</script>
Just adding type="button" in <button> tag worked. I know it's redundant but it worked!
From this:
<button id="btnDeleteRequest" class="btn btn-default" accesskey="D" onclick="ExecuteCommand('DeleteRequest',this);">
To this:
<button id="btnDeleteRequest" class="btn btn-default" type="button" accesskey="D" onclick="ExecuteCommand('DeleteRequest',this);">
I had button something like this
html:
<button onclick="captcha()" >Verify Human</button>
js:
function captcha(){
window.open(link,name,"width=800, height=600");
return false;
}
After adding type="button" in html content it worked
<button onclick="captcha()" type="button">Verify Human</button>
I know its redundant but it works ;)
Also thanks to #sojim

HTML <a> tag event order

I have a basic question regarding a tag in HTML.
Say that I've got some HTML like this
Do some work
When a user clicks on an anchor link (Do some work) which event will trigger first?
I mean whether doSomething() or href goes first.
doSomething() go first.. and if it returns false or is prevented, then the anchor link is not called.
This is what will happen:
The event will fire
the page will redirect.
But don't take my word for it, go test it out for yourself. I even got it started for you:
http://jsfiddle.net/WDdZS/
this is the simple code I used
function doSomething(){
alert("hello");
}
I added the return false, mentioned in other answers so you can see it in action. I didn't know about that actually, so always good to learn something new.
The JavaScript will execute first.

Prevent a standard a href/jquery click combo from appending # to the url?

I have a standard link setup that fires an event via jquery when clicked
Click Me
All that works great, except that when the pseudo URL is clicked, it appends a hashtag (#) to the url. This hashtag affects how my page reloads if the user decides to refresh the page later on, so i'd like to not have the hashtag appended to the url.
is this possible while still allowing my normal jquery to fire?
Thanks!
You should either return false; from the event handler of A tag
Or, use
Click Me
For those who thinks javascript: void(0) is bad practice
If you use href='#', you must take care of two things
// one
function fn() {
// code
return false;
}
// two
click
And if you forget and just write onclick="fn();" it won't work
Another thing why I used javascript: void(0); is, if the function encounters/throws an error, it wont return false
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
In end of the you click function, use:
return false;
smartass anwser: use a button.
alternative: you must make sure to trigger the preventDefault in youre jQuery event handler
$("dosomthing").click(function(e){
//make magic happen
e.preventDefault()
})
this works on html forms thats submitting and such.
note on the button thing
it is best pratice to only use a tags for link (somthing that changes the url) and buttons for other sorts of interactions.
search bots and other web crawlers expect a tags to link to a other html document (hyperlink) and up to and including html 4. or to a other point in the current document.
Does it need to be an href at all? you could do:
<span class="dosomething">Click me</span>
.
.dosomething{cursor:pointer}

Anchor tag behaving very strangely

I have an anchor tag in the website as follows:
<a href="http://www.abc.com/..." class="abc-profileinsider-popup">
<img src="..." />
</a>
The problem is that it never redirects the page to href on being clicked.
Whenever I rename the class abc-profileinsider-popup to X-profileinsider-popup where X is any string apart from abc, it works. Can anybody tell the reason behind this behaviour?
You have a javascript function somewhere that is attaching an event to elements with the class: abc-profileinsider-popup.
This function must be returning false meaning the link doesnt process. Try disabling javascript to confirm this, the link should work with Javascript disabled.
Then search for the code and see what its doing :)
I think there's an event handler in your code that prevents the default behaviour, and that it's specifically attached to elements with
abc-profileinsider-popup class.
If that is the case you should find something like:
myAnchor
.addEventListener("click", function (event) {
event.preventDefault();
});
I would search your codebase for occurrences of the string abc-profileinsider-popup.
That's an article I wrote, in case you need more info about W3C event model.

What's the effect of adding 'return false' to a click event listener?

Many times I've seen links like these in HTML pages:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
What's the effect of the return false in there?
Also, I don't usually see that in buttons.
Is this specified anywhere? In some spec in w3.org?
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.
The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.
You can see the difference with the following example:
Google
Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.
WHAT "return false" IS REALLY DOING?
return false is actually doing three very separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jquery-events-stop-misusing-return-false for more information.
For example :
while clicking this link, return false will cancel the default behaviour of the browser.
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
Here's a more robust routine to cancel default behavior and event bubbling in all browsers:
// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
if (!e)
if (window.event) e = window.event;
else return;
if (e.cancelBubble != null) e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
if (window.event) e.returnValue = false;
if (e.cancel != null) e.cancel = true;
}
An example of how this would be used in an event handler:
// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context)
{
// Find the tabStrip element (we know it's the parent element of this link)
var tabstripElement = this.parentNode;
Tabstrip.showTabByLink(tabstripElement, this);
return eventCancel(evt);
}
Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.
I believe it causes the standard event to not happen.
In your example the browser will not attempt to go to #.
Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.
If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.
In other words, adding return false stops the href from working. In your example, this is exactly what you want.
In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.
The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.
Browser hack:
http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
Return false will prevent navigation. Otherwise, the location would become the return value of someFunc
The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.
onclick="return false"
I am surprised that no one mentioned onmousedown instead of onclick. The
onclick='return false'
does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but
onmousedown='return false'
does.
In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.
See also event.preventDefault() vs. return false
I have this link on my HTML-page:
<a href = ""
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>
The function setBodyHtml() is defined as:
function setBodyHtml (s)
{ document.body.innerHTML = s;
}
When I click the link the link disappears and the text shown in the browser
changes to "new content".
But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?
It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.
In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.
This example shows why it is sometimes USEFUL to use "return false".
I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".
The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.
When using forms,we can use 'return false' to prevent submitting.
function checkForm() {
// return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
...
</form>
By default, when you click on the button, the form would be sent to server no matter what value you have input.
However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.
So, when the listener received "false", the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.

Categories

Resources