JavaScript: onclick and return false - javascript

I'm using this in my HTML:
Click
It calls the function preload() on an external js-file and works fine so far.
But i have dozens of those links and would like to remove alle those "return false" and put only one directly inside the preload()-function in the js-file.
But it will always be ignored?! Does the "return false" really only work inside the onclick="..."?

function preload () {
// some code
return false;
}
Click
or use addEventListener
For example:
Click
<script type="text/javascript">
document.querySelector('.link').addEventListener('click', function (e) {
// some code;
e.preventDefault();
}, false);
</script>

Putting return false; in the inline onclick attribute prevents the default behavior (navigation) from occurring. You can also achieve this by clobbering the onclick attribute in JavaScript (i.e. assigning the .onclick property to be a function that returns false), but that's frowned upon as old-fashioned and potentially harmful (it would overwrite any additional event listeners attached to that event, for example).
The modern way to prevent the <a> element's default click behavior from occurring is simply to call the .preventDefault() method of the triggering event from within the attached event listener. You can attach the listener the standard way, using .addEventListener()
Some examples:
// this works but is not recommended:
document.querySelector(".clobbered").onclick = function() {
return false;
};
// this doesn't work:
document.querySelector(".attached").addEventListener("click", function() {
return false;
});
// this is the preferred approach:
document.querySelector(".attachedPreventDefault").addEventListener("click", function(e) {
e.preventDefault();
});
If you click me, I don't navigate<br/>
<a class="clobbered" href="/fake">If you click me, I don't navigate</a>
<br/>
<a class="attached" href="/fake">If you click me, I navigate</a>
<br/>
<a class="attachedPreventDefault" href="/fake">If you click me, I don't navigate</a>

I think if you put it into the preload function and in the onclick event just put return false will work. Maybe you've tried this code?
Click

Try to put the return false clause into the inline function:
<input onclick="yourFunction();return false;">

I would maybe suggest not using onClick() and instead using similar jQuery.

Related

href called issue in onclick function [duplicate]

If I have this element:
Item
How can I make both href and onClick work, preferably with onClick running first?
You already have what you need, with a minor syntax change:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)
Use jQuery. You need to capture the click event and then go on to the website.
$("#myHref").on('click', function() {
alert("inside onclick");
window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
To achieve this use following html:
Item
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
No jQuery needed.
Some people say using onclick is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.
We can style a button to look like an anchor element.
From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#onclick_events
Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.
Use ng-click in place of onclick. and its as simple as that:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>

jQuery - trigger a custom event on a link

I am trying to run this custom 'getOffer()' event using jQuery
<img src="images/img.jpeg">
I have tried the following but it doesn't seem to work (I am using the Firefox Firebug console.log window)
$('a[title="Submit for offer"]').trigger('getOffer');
This is the page I am trying this on: http://bit.ly/1dpIMFk
Can anyone suggest any ideas?
<img src="images/img.jpeg">
$(document).ready(function(){
$('a[title="Submit for offer"]').trigger('getOffer');
});
function getOffer(){
alert('link clicked');
}
Seems working fine for me.I think you didnt wrapped your event trigger in document ready.
DEMO
You can use
<img src="images/img.jpeg">
Creating an custom event on jQuery
First add some identifier (id/class) to your link
<a id="linkOffer" title="Submit for offer"><img src="images/img.jpeg"></a>
Then, create your CUSTOM event.
//The function that will to the getOffer things
function getOffer() {
//Do get offer...
}
$(document).ready(function(){
//Custom event pointing to the function
$('a#linkOffer').on('getoffer',getOffer);
//Default click event
$('a#linkOffer').on('click',function(e){
//Do click stuff.
//Trigger your custom event.
$(this).trigger('getoffer');
//If you wish to not move the page, prevent the default link click behavior (moveing to other page)
e.preventDefault();
});
});
Trigger will not function because it search click attribute in element. Work around for this can be is:
Add click attribute to the element and then call the jquery function.
<button value="yu" onclick="getOffer();"/>
<script>
$("a[title='Submit for offer']").attr("onclick",$("a[title='Submit for offer']").attr('href')); // get value from href
$("a[title='Submit for offer']").trigger('click');
function getOffer()
{
alert('j');
}
</script>

Stop redirecting in javascript

Hi am developing a webpart which is included in sharepoint app and I need to stop redirection in some cases. But it doesn't work, i am trying to use
$('a').click(function(event){
event.preventDefault();
event.stopImmediatePropagation();
return false;
});
it executes and anyway redirection is done. How can I break it?
Purpose of it is: when user change sth on page I need to ask if he wants to proceed or not and then stop any redirection from othe links he might clicked.
Edit:
I just checked and with regular a with links inside it works but the problem is with link like this:
<a title="Delivery And Technology" class="ms-cui-ctl-large" id="someId" role="button" onclick="return false;" href="javascript:;" unselectable="on" mscui:controltype="" jQuery182001210093900916337="93">
which has inside this html
<SPAN class=ms-cui-ctl-largeIconContainer unselectable="on"><SPAN class=" ms-cui-img-32by32 ms-cui-img-cont-float ms-cui-imageDisabled" unselectable="on"><IMG style="TOP: -96px; LEFT: -160px" alt="Delivery And Technology" src="/_layouts/1033/images/ps32x32.png" unselectable="on"></SPAN></SPAN><SPAN class=ms-cui-ctl-largelabel unselectable="on">Delivery And<BR>Technology</SPAN>
so seems that when I click on this java script recognize it and redirects me so what i want to achive is to detect it and stop before it will redirect me to other page.
This will prevent dynamically added anchors from navigating too:
$(document).on('click', 'a', function(e){
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
steveukx suggested shorthand:
$(document).on('click', 'a', false);
My best guess is that you run this code before the DOM is ready. Try wrap it in a DOM-ready callback:
$(function () {
$('a').click(function(event){
return false;
});
});
Note that returning false is equivalent to .preventDefault() and .stopImmediatePropagation() together, so just returning false will be sufficient. In your case it might be more appropriate to just use .preventDefault() and nothing else though.
If the element has a had a handler attached before your code executes, it isn't possible to reliably remove or prevent the handler from running.
Assuming you have jQuery available, and you are running this function after the element has been added to the DOM and had its handlers attached you can replace it with an identical element:
jQuery('a').replaceWith(function(index, innerHTML) {
return jQuery(this.cloneNode(false)).html(innerHTML);
});

jQuery on(click) doesn't work but on(hover) does

After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?

jQuery: Get return of an onclick-function from an anchor

Is there a way to get the return-value of an onclick-function like confirm into a jQuery-function?
I have links which have an onclick-event for confirmation which returns true or false:
<a onclick="return confirm('Sure?');" class="delete" href="delete.php">Delete</a>
This is a given structure and I have no possibility in changing it.
But I would like to do something like this:
$('a.delete').click(function() {
if (confirm_from_onclick == true) {
//do some more before really returning true and following the link
}
});
If there is no way for you to change the HTML markup, you need to remove the complete onclick inline-handler from that node and to it in your unobtrusive event handler.
This could look like:
$(function() {
$('a').each(function(_, anchor) {
var onclk = anchor.onclick; // store the original function
anchor.onclick = null; // delete/overwrite the handler
$(anchor).bind('click', function() {
if( onclk() ) {
// do something
}
return false; // call stopPropagation() + preventDefault()
});
});
});
Since you're dealing with an onclick inline-event handler, you cannot stop or prevent that from firing with an unobtrusively bound event handler. It'll always fire first, so you need to completely remove the original event.
You don't really need to store the function, you also could just set the onclick to null and rewrite the logic in your own event handler. I did it for convenience only.
Demo: http://jsfiddle.net/em9KP/
Really simple answer and might not be exactly what you're looking for, but why not remove the "onclick" event from the anchor, then handle everything inside the click function?
As in, create the confirm dialog inside the function.
<a class="delete" href="delete.php">Delete</a>
$('a.delete').click(function(e) {
e.preventDefault();
if (confirm('Sure?')) {
//do some more before really returning true and following the link
}
});
EDIT:
Sorry! Missed the part where you mentioned that it's a set structure and you have no way of changing it. Working on an alternative.

Categories