Related
I would like to ask. I have an element
<a href='...' data-href='...'>
The problem is to prevent page redirecting after clicking this element, but still be able to run JavaScript functions by onClick action.
I was trying to set
pointer-events: none;
in my CSS, but this is blocking my elements from onClick action.
Has anybody any idea how to slove that problem?
If i understand, you would like to prevent the link from following the url.
If this is the case you could give it an id
<a id="myLink" href="...">...</a>
and then control the event using javascript
<script>
document.getElementById("myLink").addEventListener("click",function(event){
event.preventDefault();
/* your code here */
});
</script>
More info: http://www.w3schools.com/jsref/event_preventdefault.asp
preventDefault() function as the name suggests does exactly what you're looking for. Here is a good explanation of what the function does -- preventDefault()
You can use it by either of the methods shown below :-
In JS file
elem.on('click', function(e){
e.preventDefault();
});
In HTML itself
<a href='...' data-href='...' onclick='$event.preventDefault()'>
Is there a way to stop the page from redirecting on clicking a link? I'm searching for a function like preventDefault().
event.preventDefault() actually is vanilla JavaScript and can achieve what you're looking for.
For example, with the following markup:
Google
We can attach the following JavaScript to prevent the browser from heading to http://www.google.com/ when the <a> element is clicked:
document.getElementById('preventme').addEventListener(
'click', function(e) { e.preventDefault(); }, false
);
jsFiddle Demo
You can add this little function in your click handler:
event.stopPropagation()
Attach an event handler function that will "return false"
I have this code to switch a switching button image:
$("#invio_scatola_on, #invio_scatola_off").click(function(){
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});
when it is executed, the browser goes to the top of the page. why?
You probably need to prevent the default action of whatever element you click:
$("#invio_scatola_on, #invio_scatola_off").on('click', function(e){
e.preventDefault();
$("#invio_scatola_off, #invio_scatola_on").toggle();
});
Based on the few information that you've provided, if the browser is scrolling to the top, it means that you need to prevent its default behavior.
Check to see if the browser is appending "something" to the current URL...
You can prevent that like this:
$("#invio_scatola_on, #invio_scatola_off").click(function(event){
// prvent default behavior
event.preventDefault();
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});
See the jQuery event.preventDefault() for more information on how it works.
I can only guess, because you didn't post your html code. Most probably your two elements are links with href="#". After you click handler the regular action is fired, navigating to the anchor # on your site (which is the top).
Try:
$("#invio_scatola_on, #invio_scatola_off").click(function(event){
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
event.preventDefault();
});
and see if that helps. More on event cancelling with jQuery here:
http://api.jquery.com/event.preventDefault/
I think you binded the click on anchor tags with href as # so for that you can use preventDefault() of javascript like :
$("#invio_scatola_on, #invio_scatola_off").click(function(evt){
evt.preventDefault();
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});
I'm currently using <a> tags with jQuery to initiate things like click events, etc.
Example is Text
But I hate how the '#' makes the page jump to the top of the page. What can I do instead?
So this is old but... just in case someone finds this in a search.
Just use "#/" instead of "#" and the page won't jump.
In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):
$('a.someclass').click(function(e)
{
// Special stuff to do when this link is clicked...
// Cancel the default action
e.preventDefault();
});
you can even write it just like this:
im not sure its a better way but it is a way :)
Solution #1: (plain)
Text
Solution #2: (needed javascript)
Text
Solution #3: (needed jQuery)
Text
<script>
$('a.someclass').click(function(e) {
e.preventDefault();
});
</script>
You can use event.preventDefault() to avoid this. Read more here: http://api.jquery.com/event.preventDefault/.
Just use <input type="button" /> instead of <a> and use CSS to style it to look like a link if you wish.
Buttons are made specifically for clicking, and they don't need any href attributes.
The best way is to use onload action to create the button and append it where you need via javascript, so with javascript disabled, they will not show at all and do not confuse the user.
When you use href="#" you get tons of different links pointing to the same location, which won't work when the agent does not support JavaScript.
If you want to use a anchor you can use http://api.jquery.com/event.preventDefault/ like the other answers suggested.
You can also use any other element like a span and attach the click event to that.
$("span.clickable").click(function(){
alert('Yeah I was clicked');
});
$('a[href="#"]').click(function(e) {e.preventDefault(); });
You can use #0 as href, since 0 isn't allowed as an id, the page won't jump.
Text
There are 4 similar ways to prevent the page from jumping to the top without any JavaScript:
Option 1:
Link
Option 2:
Link
Option 3:
Link
Option 4 (Not recommended):
Link
But it's better to use event.preventDefault() if you are handing the click event in jQuery.
Just use
Text
JQUERY
$('.someclass').click(function(e) { alert("action here"); }
If the element doesn't have a meaningful href value, then it isn't really a link, so why not use some other element instead?
As suggested by Neothor, a span is just as appropriate and, if styled correctly, will be visibly obvious as an item that can be clicked on. You could even attach an hover event, to make the elemnt 'light up' as the user's mouse moves over it.
However, having said this, you may want to rethink the design of your site so that it functions without javascript, but is enhanced by javascript when it is available.
Links with href="#" should almost always be replaced with a button element:
<button class="someclass">Text</button>
Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.
You could just pass an anchor tag without an href property, and use jQuery to do the required action:
<a class="foo">bar</a>
I have used:
Text
I've always used:
Some text
when trying to prevent the page jump. Not sure if this is the best, but it seems to have been working well for years.
The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.
$('body').on('click', 'a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.
Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:
$('body').on('click', '.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });
This way it was targeted, and didn't affect anything thing else on the page.
You can also return false after processing your jquery.
Eg.
$(".clickableAnchor").live(
"click",
function(){
//your code
return false; //<- prevents redirect to href address
}
);
I use something like this:
Text
To prevent the page from jumping, you need to call e.stopPropagation(); after calling e.preventDefault();:
stopPropagation prevents the event from going up the DOM tree. More info here: https://api.jquery.com/event.stoppropagation/
If you want to migrate to an Anchor Section on the same page without page jumping up use:
Just use "#/" instead of "#"
e.g
Home
About
contact page will not jump up on click..
Adding something after # sets the focus of page to the element with that ID. Simplest solution is to use #/ even if you are using jQuery. However if you are handling the event in jQuery, event.preventDefault() is the way to go.
The Link and Link does not work if one has to click on the same input more than once.. it only takes in 1 event click for each on multiple inputs.
still the best way to go is with Link
then,
event.preventDefault();
The simplest one for me was to do this.
Some text
The reason for using JS is that most modern sites rely on it.
Many times I've seen links like these in HTML pages:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
What's the effect of the return false in there?
Also, I don't usually see that in buttons.
Is this specified anywhere? In some spec in w3.org?
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.
The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.
You can see the difference with the following example:
Google
Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.
WHAT "return false" IS REALLY DOING?
return false is actually doing three very separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jquery-events-stop-misusing-return-false for more information.
For example :
while clicking this link, return false will cancel the default behaviour of the browser.
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
Here's a more robust routine to cancel default behavior and event bubbling in all browsers:
// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
if (!e)
if (window.event) e = window.event;
else return;
if (e.cancelBubble != null) e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
if (window.event) e.returnValue = false;
if (e.cancel != null) e.cancel = true;
}
An example of how this would be used in an event handler:
// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context)
{
// Find the tabStrip element (we know it's the parent element of this link)
var tabstripElement = this.parentNode;
Tabstrip.showTabByLink(tabstripElement, this);
return eventCancel(evt);
}
Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.
I believe it causes the standard event to not happen.
In your example the browser will not attempt to go to #.
Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.
If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.
In other words, adding return false stops the href from working. In your example, this is exactly what you want.
In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.
The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.
Browser hack:
http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
Return false will prevent navigation. Otherwise, the location would become the return value of someFunc
The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.
onclick="return false"
I am surprised that no one mentioned onmousedown instead of onclick. The
onclick='return false'
does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but
onmousedown='return false'
does.
In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.
See also event.preventDefault() vs. return false
I have this link on my HTML-page:
<a href = ""
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>
The function setBodyHtml() is defined as:
function setBodyHtml (s)
{ document.body.innerHTML = s;
}
When I click the link the link disappears and the text shown in the browser
changes to "new content".
But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?
It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.
In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.
This example shows why it is sometimes USEFUL to use "return false".
I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".
The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.
When using forms,we can use 'return false' to prevent submitting.
function checkForm() {
// return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
...
</form>
By default, when you click on the button, the form would be sent to server no matter what value you have input.
However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.
So, when the listener received "false", the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.