Sending a value to the database without rendering the Flask template [duplicate] - javascript

On using Google I found that they are using onclick events in anchor tags.
In more option in google header part, it looks like normal a tag, but onclicking it doesn't get redirected but opened a menu. Normally when using
<a href='more.php' onclick='show_more_menu()'>More >>></a>
It usually goes to 'more.php' without firing show_more_menu(), but I have show a menu in that page itself. How to do like google?

If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

You can even try below option:
More >>>

From what I understand you do not want to redirect when the link is clicked.
You can do:
<a href='javascript:;' onclick='show_more_menu();'>More ></a>

Use following code to show menu instead go to href addres
function show_more_menu(e) {
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();
}
More >>>

One more solution that prevents default action even if the javascript function returns any value.
<a href="www.any-website.com" onclick='functionToRun();return false;'>

1) Link to work
<a href="#" onClick={this.setActiveTab}>
...View Full List
</a>
setActiveTab = (e) => {
e.preventDefault();
console.log(e.target);
}

Related

Using 'href="#"' needs 2 Back presses in some browsers

I have javascript that uses 'href="#"' to call a function when it's clicked. The problem is that when I run it on Chrome, I need 2 Back presses to return to the referrer page, but on Opera, I only need 1 Back press.
I read the details about using 'href="#"' here:
What is href="#" and why is it used?
here is my test code:
<p>
<script type="text/javascript">
function testOnClick(){
document.write("onClick() support was detected!<br>");
}
</script>
</p>
Clicking on the link should clear the screen and display progress text<br />
<a onclick="testOnClick();" href="#!">
Click here to test onClick
</a>
You might need to use event.preventDefault();
function testOnClick(event) {
event.preventDefault();
document.write("onClick() support was detected!<br>");
}
It prevents your navigator to navigate to the # link, thus, having to press back.
You can also get similar functionality by using a different element and making it look like a link. If you aren't navigating the user to a different section of the page or a new page, for example, you probably should be using the <a> tag.
Here's a fiddle for what I mean: http://jsfiddle.net/2ph2d2gd/
The use case for this would be to open a modal, or do some other action that doesn't necessarily navigate the user anywhere. I don't know your specific circumstances, so you may or may not want to use something like this.
Note: I used alert instead of document.write because jsfiddle doesn't allow the latter.
HTML:
Clicking on the link should clear the screen and display progress text<br />
<span class="link" onclick="testOnClick();">
Click here to test onClick
</span>
CSS:
.link{
text-decoration:underline;
color:blue;
cursor:pointer;
}
Javascript:
function testOnClick(){
alert("onClick() support was detected!");
}
I've had good results leaving the href blank in this scenario. It doesn't reload the page with "#" at the end of the URL and events still fire.
I'm not sure how well that works with JS onclick, but you could replace that with jQuery.
<script type="text/javascript">
$(function() {
$("#link").on("click", function() {
alert("click");
});
});
</script>
<a id="link" href="">
Click here to test onClick
</a>
If you 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)"
More information about why can be found in this question

How to avoid page refreshing on anchor (<a></a>) tag click?

I'm creating a dynamic website. My problem is when i click on the following tag:
<a class="s-inte" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>
The page gets refreshed, How do I avoid this page refresh?
What you want to accomplish is to update some counter of interestings w/o refreshing the page?
You should do it using AJAX techniques, this is what AJAX was invented for.
Consider the following code, it's top easy (jQuery library required):
Interesante
<script>
$(function(){
$("a.counter").click(function()
{
$.get("set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1" );
.... // you can do some animation here, like a "Liked!" popup or something
return false; // prevent default browser refresh on "#" link
});
});
</script>
you need to prevent default action on the click event.
You can do a simple inline handler which will return false
<a class="s-inte" onclick="return false" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>
or write a jQuery handler which will do the same
$('.s-inte').click(function(e){
e.preventDefault()
})
If you are dynamically loading the content using ajax. You should probably call it in this way. This way it will work for every anchor with .s-inte class, no matter it's added dynamically or statically.
$(document).on('click', '.s-inte',function(e){
e.preventDefault();
// Do more stuff every anchor click here...
});
put href="javascript:void(0)"

OnClick opens new windows but also changes current window

I'm using IE8. I've setup the following link:
<a href="terms.html" onclick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600')" />Terms & Conditions</a>
When I click it. I get the pop up the way I want. But it also sets the current windows to the same URL. I know I'm missing something silly. Just can figure it out.
Thanks!
Add return false; after window.open like below :
<a href="terms.html" onclick="window.open(this.href, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600');return false;" />Terms & Conditions</a>
Since you're clicking a <a>-link, your browser will automatically follow it. You need to make the onclick method return false for it to not open that page in your current window. It's also good to extract all JavaScript code from HTML, so that's something you should look into. However, this solution seems to do the trick:
HTML
<a href="terms.html" onclick="return openWindow('terms.html')" />Terms & Conditions</a>
JavaScript
function openWindow(href) {
window.open(href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600');
return false;
}

href="javascript:" vs. href="javascript:void(0)"

Our web app is rendered totally on the browser.The server only talks to the browser through JSON messaging.
As a result, we only need a single page for the app and mostly all the <a> tags do not have a real href pointing to other pages.
In my quest of removing unnecessary things I was wondering if I can get rid of the zillions of void(0) we have in our code, as they seem useless:
<a onclick="fn()">Does not appear as a link, because there's no href</a>
fn is called
fn is called too!
Does anybody knows if using href="javascript:" can cause a problem?
It works even on IE7...
Please don't spend your valuable time to tell me inline javascript is bad, as this is generated by a template engine :)
It does not cause problems but it's a trick to do the same as PreventDefault
when you're way down in the page and an anchor as:
click here
you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);
regarding your examples
<a onclick="fn()">Does not appear as a link, because there's no href</a>
just do a {text-decoration:underline;} and you will have "link a-like"
fn is called
fn is called too!
it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.
When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:
javascript:"hello"
The result is a new page with only the word "hello". Now change it to:
javascript:void "hello"
...nothing happens.
When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:
javascript:undefined;
javascript:void 0;
javascript:
With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().
As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.
Using 'javascript:void 0' will do cause problem in IE
when you click the link, it will trigger onbeforeunload event of window !
<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
alert( 'oops!' );
};
</script>
</body>
</html>
This method seems ok in all browsers, if you set the onclick with a jQuery event:
Click me!
As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.
you could make them all #'s.
You would then need to add return false; to the end of any function that is called onclick of the anchor to not have the page jump up to the top.
I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application
a {
text-recoration: underline;
cursor: pointer;
}
javascript:void(0); --> this executes void function and returns undefined. This could have issues with IE.
javascript:; --> this does nothing. safest to create dead links.
'#' --> this means pointing to same DOM, it will reload the page on click.
Why have all the click events as a href links?
If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

JavaScript - href vs onclick for callback function on Hyperlink

I want to run a simple JavaScript function on a click without any redirection.
Is there any difference or benefit between putting the JavaScript call in the href attribute (like this):
....
vs. putting it in the onclick attribute (binding it to the onclick event)?
bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
even better 1:
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
even better 2:
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.
In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.
In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.
However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
$('a#link').click(function(){ /* ... action ... */ })
</script>
EDITOR WARNING: See the comments, the use of 'nohref' is incorrect in this answer.
I use
Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>
A long way around but it gets the job done. use an A style to simplify
then it becomes:
<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style>
<a nohref onClick="alert('Hello World')">HERE</a>
The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.
Best is to bind an event handler to the element as numerous other people have stated, however, do stuff works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV
Another interesting tid-bit....
onclick & href have different behaviors when calling javascript directly.
onclick will pass this context correctly, whereas href won't, or in other words no context won't work, whereas <a onclick="javascript:doStuff(this)">no context</a> will.
Yes, I omitted the href. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);" for good measure
the best way to do this is with:
The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses
dojo.stopEvent(event);
to do so.
In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.
This works
Click Here
Having javascript: in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).
A better practice would be the second way, to put your javascript into the onclick attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.
it worked for me using this line of code:
<a id="LinkTest" title="Any Title" href="#" onclick="Function(); return false; ">text</a>
First, having the url in href is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Typical Bind Method
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
No Bind Method
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
Google
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.
The most upvoted answer is obsolete today
I would recommend the exact opposite, see step by step with reasons:
good:
<a id="myLink" href="javascript:MyFunction();">link text</a>
It depends, might be good, because crawlers follows href targets and if there is any meaningful content produced by MyFunction() (dynamic link), it is followed more likely than in the click event, which may have multiple or none listeners.
bad:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
# means meaningless link, crawlers are often interested only in first x links, so it can prevent them to follow some meaningful links later in the page.
worse:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
Same as previous plus return false prevents following the link. If some other scripts want to add another listener and update the target (say to redirect via proxy), they can't without modifying the onclick (okay, it's just a minor setback as such use cases are rather theoretical).
worst:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
jQuery is outdated in 2020+ and should not be used in new projects.
Events in href
The href attribute handler doesn't get the event object, so the handler doesn't implicitly see which link was the source. You can add it in onclick handler, which fires before the href is followed:
<a href="javascript:my_function(event2)" onclick="event2=event">
JS based link
</a>
<script>
function my_function(e) {
console.log(e.target); // the source of the click
if(something) location.href = ...; // dynamic link
}
</script>
One more thing that I noticed when using "href" with javascript:
The script in "href" attribute won't be executed if the time difference between 2 clicks was quite short.
For example, try to run following example and double click (fast!) on each link.
The first link will be executed only once.
The second link will be executed twice.
<script>
function myFunc() {
var s = 0;
for (var i=0; i<100000; i++) {
s+=i;
}
console.log(s);
}
</script>
href
onclick
Reproduced in Chrome (double click) and IE11 (with triple click).
In Chrome if you click fast enough you can make 10 clicks and have only 1 function execution.
Firefox works ok.
<hr>
<h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
<button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
<div class="pull-right">
<button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
});
</script>
I experienced that the javascript: hrefs did not work when the page was embedded in Outlook's webpage feature where a mail folder is set to instead show an url
click here
I cant belive that +13 years later, all of these answers are semantically incorrect! An anchor element <a>:
...with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
Content within each should indicate the link's destination. If the href attribute is present, pressing the enter key while focused on the element will activate it.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
Therefore, using an href= for javascript is bad practice and poor web semantics. You should rather be using an onclick= event handler attribute on a button element, as:
The HTML element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs a programmable action, such as submitting a form or opening a dialog.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
and the event handler onclick=:
All event handler attributes accept a string. The string will be used to synthesize a JavaScript function like function name(/args/) {body}, where name is the attribute's name, and body is the attribute's value.
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#event_handler_attributes
As you are not navigating to a URL or a Link destination, but rather triggering a Javascript function the correct way to do this is to use onclick. And if you need the style of an anchor tag on a button, just use CSS.
The bottom line is: just because you can do it doesn't mean you should.
This works as well
<a (click)='myFunc()'>Click Here </a>
(onclick) did not work for me in an Angular project with bootstrap.

Categories

Resources