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.
Related
JS Fiddle Example
I'm opeing the dropdown boxes using the 'FOO', 'BOO' items in the navigation bar and I'm closing them when a click event occurs outside using the following code which is working fine.
$(document).on('click', '.dd-box', function() {
// Comment out the return statement below and the links will start working.
return false
});
The problem that I'm experiencing is that this is also stopping the links within the dropdown boxes from being visted.
The reason I need this code is because I don't want the dropdown boxes to close when click events happen within them.
I'm trying to avoid using hacks like window.open to force the link from being visited, any ideas?
you should put stopPropagation
$(document).ready(function() {
$("a").click(function(e) {
e.stopPropagation();
});
...
see JSFiddle
Currenlty when a page is posting back or something else is going on I display a big grey div over the top of the whole page so that the user can't click the same button multiple times. This works fine 99% of the time, the other 1% is on certain mobile devices where the user can scroll/zoom away from the div.
Instead of trying to perfect the CSS so that it works correctly (this will be an on going battle with new devices) I've decided to just stop the user from being able to click anything. Something like $('a').click(function(e){e.preventDefault();}); would stop people from clicking anchor tags and navigating to the link but it wouldn't stop an onclick event in the link from firing.
I want to try to avoid changing the page too radically (like removing every onclick attribute) since the page will eventually have to be changed back to its original state. What I would like to do is intercept clicks before the onclick event is executed but I don't think that this is possible. What I do instead is hide the clicked element on mouse down and show it on mouseup of the document, this stops the click event firing but doesn't look very nice. Can anyone think of a better solution? If not then will this work on every device/browser?
var catchClickHandler = function(){
var $this = $(this);
$this.attr('data-orig-display', $this.css('display'));
$this.css({display:'none'});
};
var resetClickedElems = function(){
$('[data-orig-display]').each(function(){
$(this).css({display:$(this).attr('data-orig-display')}).removeAttr('data-orig-display');
});
};
$('#btn').click(function(){
$('a,input').on('mousedown',catchClickHandler);
$(document).on('mouseup', resetClickedElems);
setTimeout(function(){
$('a,input').off('mousedown',catchClickHandler);
$(document).off('mouseup', resetClickedElems);
}, 5000);
});
JSFiddle: http://jsfiddle.net/d4wzK/2/
You could use the jQuery BlockUI Plugin
http://www.malsup.com/jquery/block/
You can do something like this to prevent all actions of the anchor tags:
jQuery('#btn').click(function(){
jQuery('a').each(function() {
jQuery(this).attr('stopClick', jQuery(this).attr('onclick'))
.removeAttr('onclick')
.click(function(e) {
e.preventDefault();
});
});
});
That renames the onclick to stopclick if you need to revert later and also stops the default behavior of following the href.
document.addListener('click',function(e){e.preventDefault()})
Modified-
Its your duty to remove the click event from the document after you are done accomplishing with your task.
Eg -
function prevent(e){
e.preventDefault()
}
//add
document.addListener('click',prevent)
//remove
document.removeListener('click',prevent)
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);
});
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.
I've got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when I click these questions, the window jump to the top of the screen. This is not a huge problem, but I find it annoying, because I have to scroll down to the question again.
The links simply looks like this:
Myquestion
And I've used jQuery and .click as event-listener.
Are there any simple ways to avoid this, or do I have to use .scroll and finding the coordinates of the question? I'd rather avoid this.
EDIT: I know that I can use anchors to do this, but I'd like to avoid any jumping of the screen at all.
You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.
Example:
$("#myID").click(function(e) {
e.preventDefault();
// Do your stuff
});
Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.
You can do it very simple:
Just add ! in the end of your href:
Myquestion
The alternative jQuery ways are:
$("#myID").click(function(e) {
e.preventDefault(); // one way
return false; // second way prevent default click action from happening
});
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
e.preventDefault()alone did not work in older versions of IE.
Actually, the easiest way to do this is to remove the href attribute from your anchor tag. As of HTML5, anchor tags don't need to include href attributes to be semantic.
So
<a id="myID">Myquestion</a>
instead of
Myquestion
This works in IE8+, Chrome, and Firefox. Note that :link css styles won't apply to anchor tags that don't include href attributes.
If you need the href attribute and/or IE7 compatibility, then
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
is probably the best way to go.
$('a').click( function() {
if ($(this).attr("href") == window.location.hash) {
event.preventDefault()
}
});
You are looking for event.preventDefault (see jQuery API).
$(...).click(function(e) {
e.preventDefault();
// your code
});
Example with nice scrolling to answer content:
$("#question_title").click(function(){
var $answer=$("#answer");
$answer.slideDown();
$.scrollTo( $answer, 800 );
return false;
});
I'm used jQuery scrollTo plugin.
Inside your function of:
And I've used jQuery and .click as event-listener.
Will look something like:
$("#myID").click(function(){});
Change this to (don't forget the param e inside function(e):
$("#myID").click(function(e){
e.preventDefault();
});
$('body').on('click', '[href^=#]', function (e) {
e.preventDefault()
});
if the selector ex.."body" is there during the initial render then use the any selector .. id ... to target the general to have jQuery (as of 1.8.2) iterate over. the "On handler invoke a method called "bind" which is used for newly added content to the DOM",. Using the "[href^=#] will select any href that are in the section tag but you can replace section with anything or nothing and it applies a cancellation to the click event. This technique is great for dynamically created content to the DOM
If you add a "\" to the "#" it will prevent from going to the top.
Myquestion
HTML:
<a id="like-post" href="#\">like</a>
JavaScript:
$('body').delegate('#like-post','click',function(e) {
e.preventDefault();
.....
});