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);
});
Related
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.
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()
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.
For some reason when this JQuery call is made the page refreshes. I was lead to believe that a return false; at the end of a JQuery function would cause the page not to reload, but apparently this is not the case? Here is my stripped down code:
$(function() {
$(".vote").click(function() {
return false;
});
});
When I click on the vote button the page is refreshed. I know that this code is being called because if I replace return false with alert('asdf'); the alert appears.
Often when you want to prevent a link from being followed or a form from submitting, you want to tell the event to preventDefault():
$('a').click(function(e){
e.preventDefault();
});
Try this:
$(function() {
$(".vote").click(function(e) {
e.preventDefault();
});
});
You can't put a div in an a: div is block-level element, a is inline, and HTML does not allow block elements inside inline elements. Browsers will try to automatically correct this by rearranging your DOM tree somehow (for example, <a><div></div></a> might end up as <a></a><div><a></a></div><a></a>); which leads to all sort of funny behavior. In Firefox you can use 'view selection source' (or, of course, Firebug) to check what happened.
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>