href called issue in onclick function [duplicate] - javascript

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>

Related

continue click action after preventDefault [duplicate]

How could one trigger the default action/event of a HTML link (anchor element)? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it.
Just using .click() does not seem to work.
$('#alink').click();
// the nothing happening
For this HTML:
<a id="alink" href="http://google.com" target="_blank">a link</a>
Example fiddle: http://jsfiddle.net/dCfD8/
I'd rather not create a new window in JavaScript (and take care of whatever else needs to be handled when a link is clicked).
You can trigger the click event using a simple trigger method in jQuery.
$('#alink').trigger('click');
Beware though, that even in the event gets fired, the browser will not follow the link href. The only way to follow the href is to actually click it with the mouse yourself.
As far as I know, there is no way to force a link to behave as if it were clicked. You have to change the document location or something like that to actually navigate between pages.
Expanding on Fabio Cicerchia's comment to his own post: You can use window.open:
var link = $('#alink');
var target = link.attr("target");
window.open(link.attr("href"), target ? target : "_self");
<script src='jquery lib source' ></script>
<script>
function force()
{ ...do something...to fill page2
$('#gopage2').trigger('submit');
}
</script>
<form action='#page2' id='gopage2'>
</form>
...
<span name='#page2'>This is page2</span>
try this:
$('#alink').trigger('click');

JavaScript: onclick and return false

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.

Anchor "javascript:void(0)" causing window.onbeforeunload to fire on IE

I am using a drop down widget called Chosen which has an anchor with a href javascript:void(0). When I click on the drop down it works but on IE it fires a new onbeforeunload event which is frustrating because the application confirms if you want to leave. And obviously you don't want to have those questions when you are inputting form data.
Is there a way to get rid of this problem without altering Chosen library?
Unfortunately this:
window.onbeforeunload = function (e) {
console.log(window.location);
};
Does not log javascript:void(0) either, so, I can't use it to check the target URL.
This behavior occurs in IE9 at least, and that's what I'm concerned (not the older IEs).
The only solution I can see is to add returning of false to the onclick event handler of the links. It will tell IE that you're not planning to change the page by clicking on the link.
Link
The same can be written this way:
<script>
function doSomething() {
// do Something
return false;
}
</script>
Link
I ended up listening to click events against the anchor and cancel the event to prevent onBeforeUnload from firing:
$chosen.find('.chzn-single').click(function() {
return false;
});
I know that this is pretty old...But I have come across this recently for my work. We are unfortunately still forced to support IE9. We are using Angular.js on this project that will dynamically load new content onto a page when the user clicks on an anchor tag with a data-ng-click.
In your example all you would have to do is pass the event and within the function prevent the default action and stop it from bubbling up. To do this all you would have to do is this:
// Inside the HTML
{...}
Link
{...}
<script>
function doSomething(evt) {
evt.preventDefault();
evt.stopPropagation();
// Do Something
};
</script>
{...}
In Angular all I did was the following:
// Inside the View
Add Stuff
// Inside the controller
function addStuff($event) {
$event.preventDefault();
$event.stopPropagation();
// Do Something
};
I hope that this isn't too late and I hope that it helps others.
Had the same problem. Just found your question. My solution is, you need to add onclick attribute to every chosen dropdown list anchor tag and call window.onbeforeunload = null
In my case, I've put
$(".chzn-single").attr("onclick", "window.onbeforeunload = null;");
After setting up chosen library and it works fine
don't use href's for this. A simple solution with minimal extra work:
i prefer to use a CSS class that simulates an href, obviously you will change the color and styling of this class to fit your website, but for this purposes, it's the standard blue underlined link
<style>
.linkSimulate
{
cursor: pointer;
COLOR: blue;
text-decoration: underline;
}
</style>
then use a simple anchor
<a onclick = "do_save();" class ="linkSimulate">Link</a>
Even if this question is old, i've anhanced the answer of #Bartosz, fixing the issue in the comment of #Oiva Eskola:
Wouldn't this prevent the window.onbeforeunload from working after clicking a chosen link element? – var thisOnClick;
Below is my solution to properly create the HTML onclick property, to not override or cancel the event:
var thisOnClick;
$.each( $(' .container a '), function(){
thisOnClick = $(this).attr('onclick');
if ( typeof thisOnClick == 'undefined' ) {
$(this).attr('onclick', 'window.onbeforeunload = null;');
} else if ( typeof thisOnClick == 'string' && thisOnClick.indexOf('window.onbeforeunload') == -1 ) {
$(this).attr('onclick', thisOnClick + 'window.onbeforeunload = null;');
}
});

Why does clicking a link go to the top of the page?

This may sound a weird question,
I have a page which has a link:
<a href="#" class="emails" > Email to Friends </a>
Now I have an event attach to the anchor tag so that on click the given div toggle it state.
The Javascript Code look like this:
$(document).ready(function() {
$(".emails").bind("click",function() {
$("div#container").toggle
})
})
Now the above code and all of it works fine,
but here the big deal,
when I click the given link the my focus of the page move to top of the page,
and I have to scroll all the way down to see the change.
Can anyone help me on this?
It does this because the href="#" is an empty anchor. Anchors are used for linking to specific spots within a page. An empty anchor results in the page going back to the top.
To fix this in your javascript, you need to prevent the click event from propagating or "bubbling" up the DOM. You can do this by returning false from your click event.
$(document).ready(function() {
$(".emails").bind("click",function() {
$("div#container").toggle();
return false; // prevent propagation
})
});
You can also make the event available in the bind's click handler function by using an argument, usually named e. Having access to the event allows you to call methods on it such as .preventDefault().
$(document).ready(function() {
$(".emails").bind("click", function(event) {
$("div#container").toggle();
event.preventDefault(); // this can also go at the start of the method if you prefer
})
});
This will solve all cases where anchor is empty.
$(document).ready(function () {
$('a').click(function () {
$('[href = #]');
return false;
});
});
This comes from the href='#' in the a. Just remove this tag. But then it's technically not a link any more, so the cursor will default to a text-selector when over it. You can override this using cursor:pointer in your CSS. See the left menu on this website for reference.
Use:
<a href="javascript:void(0)" class="emails" > Email to Friends </a>
Or, using jQuery,
$(document).ready(function() {
$(".emails").attr("href","javascript:void(0)");
})
Void(0) returns a.. well.. it doesn't return anything. The browser knows how to go to nothing (i.e., what would happen if you did href=""), and to # (# is the top of the page), but not how to go to a void "value".
Whenever you put a javascript: in an attribute, the attribute's value gets set to the return value of the code inside. The code is called the first time the attribute is accessed.
But, void(0) returns nothing. Not even "". The browser takes this to meant that the link is not a link at all.

call javascript function on hyperlink click

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>

Categories