Link versus onClick - javascript

I have a web application that exclusively uses AJAX so there are no full refreshes and everything is set up as
<a href="javascript:...()">
It works really well on Chrome and Firefox but IE asks to confirm the page reload every time I click on anything. Would it be better to change the links to
href="#"
and make the functionality into onClick?
Thanks.

Just stop using inline javascript all together. You don't need it.
Output the id associated to the element in a data attribute:
listitem1
Now you can bind to those click events from an external js file:
$(document).ready(function(){
$(".list-item").click(function(e){
e.preventDefault(); // stop jump to top
var theId = $(this).attr("data-id"); // get the id
someFunction(theId); // execute some terribly written function
});
});
This does work cross-browser.

With "href='#'" you will probably need to preventDefaults on your JS function so the page doesn't go to top because of the '#' anchor.
I would do:
HTML
<a href="javascript:void(0)" class="someclass" rel='2'>
JS
$('.someclass').on('click', function(){
var value = $(this).attr('rel');
// use 'value' as you would normaly do with your function(2)
});
Or this one:
HTML
<a href="#" class="someclass" rel='34'>
JS
$('.someclass').on('click', function(e){
e.preventDefault();
var value = $(this).attr('rel');
// use 'value' as you would normaly do with your function(34)
});

Use .
Also, make sure that in your javascript function you stop the event from propagating like this:
function myFunction() {
//Your code here
event.preventDefault ? event.preventDefault() : event.returnValue = false;
return false;
}
This will stop the browser from jumping to the top of the page and is IE compatible, since IE does not use event.preventDefault()

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>

trigger('click') doesn't work on anchors without an actuall link in the href ( js function in the href attrbute )

i have some links for confirming comments
<a class="confirm_btn" href="javascript:confirm_ajax(17)" id="confirm_17">Confirm</a>
<a class="confirm_btn" href="javascript:confirm_ajax(20)" id="confirm_20">Confirm</a>
i want to be able to confirm all at once with one click , i know it's probably better to get all ids in an array and send them with one ajax call to backend script but for some reason i prefer not to do that and click each button .
here is my jq code
function confirm_all(){
$('.confirm_btn').each(function(index, element) {
$(this).trigger('click');
// also i've tried $(this).click();
console.log($(this).attr('id'));
});
}
when i run this i get the console.log result
confirm_17
confirm_20
confirm_22
confirm_33
confirm_34
but the click part doesn't work , it suppose to fire confirm_ajax function ... no error in the firebug .... if i click on the buttons they work fine
trigger('click') will only invoke attached event handlers; if you have JavaScript hrefs, they won't be triggered.
You could try attaching regular click handlers to your links, or you could do something like this instead:
var idFormat = /confirm_(\d+)/;
$('.confirm_btn').each(function() {
var btn = $(this);
var id = parseInt(idFormat.exec(btn.attr('id'))[1], 10);
confirm_ajax(id);
});

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);
});

Append an onClick event to an anchor tag using jquery?

I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});

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