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.
Related
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
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}
I inspected the inbox link in hotmail using firebug and saw something like that:
<a ... href="javascript:; .... />
I just can't figure out how the postback is realizing when I click the link. And what does "javascript:;" mean while it doesn't refer to any function?
The javascript: part there is a pseudo-protocol meaning that the URI should be interpreted as JavaScript code. The ; immediately after it is a statement terminator. Assuming that nothing else follows, it basically makes the link do nothing when clicked.
If something is happening when the link is clicked, I'm guessing a click event handler has been attached to it or one of its ancestor elements. click bubbles up the DOM, so you don't have to watch it actually on the element itself.
You won't necessarily see those event handler attachments in the HTML; the page may well use unobtrusive techniques to hook up the handler later.
Gratuitous live example #1 (hooking the click on the link unobtrusively)
Gratuitous live example #2 (hooking the click on an ancestor element)
It's evaluating the expression ;, which doesn't do anything. It's just there so that there's something in the href (otherwise it won't behave like a link).
The actual behavior is being wired-up somewhere else. For example, it might be wireup up with something like this jQuery statement: $('#inboxLink').click(goToInboxFunction)
Or, as #T.J. Crowder points out, the click handler could be wired-up higher up in the DOM and use event bubbling the capture it for this link.
I'm currently using <a> tags with jQuery to initiate things like click events, etc.
Example is Text
But I hate how the '#' makes the page jump to the top of the page. What can I do instead?
So this is old but... just in case someone finds this in a search.
Just use "#/" instead of "#" and the page won't jump.
In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):
$('a.someclass').click(function(e)
{
// Special stuff to do when this link is clicked...
// Cancel the default action
e.preventDefault();
});
you can even write it just like this:
im not sure its a better way but it is a way :)
Solution #1: (plain)
Text
Solution #2: (needed javascript)
Text
Solution #3: (needed jQuery)
Text
<script>
$('a.someclass').click(function(e) {
e.preventDefault();
});
</script>
You can use event.preventDefault() to avoid this. Read more here: http://api.jquery.com/event.preventDefault/.
Just use <input type="button" /> instead of <a> and use CSS to style it to look like a link if you wish.
Buttons are made specifically for clicking, and they don't need any href attributes.
The best way is to use onload action to create the button and append it where you need via javascript, so with javascript disabled, they will not show at all and do not confuse the user.
When you use href="#" you get tons of different links pointing to the same location, which won't work when the agent does not support JavaScript.
If you want to use a anchor you can use http://api.jquery.com/event.preventDefault/ like the other answers suggested.
You can also use any other element like a span and attach the click event to that.
$("span.clickable").click(function(){
alert('Yeah I was clicked');
});
$('a[href="#"]').click(function(e) {e.preventDefault(); });
You can use #0 as href, since 0 isn't allowed as an id, the page won't jump.
Text
There are 4 similar ways to prevent the page from jumping to the top without any JavaScript:
Option 1:
Link
Option 2:
Link
Option 3:
Link
Option 4 (Not recommended):
Link
But it's better to use event.preventDefault() if you are handing the click event in jQuery.
Just use
Text
JQUERY
$('.someclass').click(function(e) { alert("action here"); }
If the element doesn't have a meaningful href value, then it isn't really a link, so why not use some other element instead?
As suggested by Neothor, a span is just as appropriate and, if styled correctly, will be visibly obvious as an item that can be clicked on. You could even attach an hover event, to make the elemnt 'light up' as the user's mouse moves over it.
However, having said this, you may want to rethink the design of your site so that it functions without javascript, but is enhanced by javascript when it is available.
Links with href="#" should almost always be replaced with a button element:
<button class="someclass">Text</button>
Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.
You could just pass an anchor tag without an href property, and use jQuery to do the required action:
<a class="foo">bar</a>
I have used:
Text
I've always used:
Some text
when trying to prevent the page jump. Not sure if this is the best, but it seems to have been working well for years.
The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.
$('body').on('click', 'a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.
Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:
$('body').on('click', '.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });
This way it was targeted, and didn't affect anything thing else on the page.
You can also return false after processing your jquery.
Eg.
$(".clickableAnchor").live(
"click",
function(){
//your code
return false; //<- prevents redirect to href address
}
);
I use something like this:
Text
To prevent the page from jumping, you need to call e.stopPropagation(); after calling e.preventDefault();:
stopPropagation prevents the event from going up the DOM tree. More info here: https://api.jquery.com/event.stoppropagation/
If you want to migrate to an Anchor Section on the same page without page jumping up use:
Just use "#/" instead of "#"
e.g
Home
About
contact page will not jump up on click..
Adding something after # sets the focus of page to the element with that ID. Simplest solution is to use #/ even if you are using jQuery. However if you are handling the event in jQuery, event.preventDefault() is the way to go.
The Link and Link does not work if one has to click on the same input more than once.. it only takes in 1 event click for each on multiple inputs.
still the best way to go is with Link
then,
event.preventDefault();
The simplest one for me was to do this.
Some text
The reason for using JS is that most modern sites rely on it.
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.