.preventDefault() method not working with .on() - javascript

I'm trying to prevent the default behavior of clicking on an anchor element like this:
<a class="btn btn-default start-match" data-call="start" href="/matches/256/start.json" data-method="patch" data-model="Match" rel="nofollow">
<span class="glyphicon glyphicon-screenshot"></span> Iniziata
</a>
with a javascript like this:
$(document).on(
'click',
"a",
function(event) {
event.preventDefault();
event.stopPropagation();
}
);
but this code is not preventing the default behavior, and the link is followed. why?
my jquery version is 1.10 and I'm using turbolinks

As per i know in anchor tag first preference given to HREF then onclick event. so by default HREF url get call first.
If you dont want to call anchor url then you can replace HREF tag with
....

It seems like event.preventDefault() works only from jQuery 1.7
The same JavaScript code with different results:
$(document).ready(function () {
$("a").on('click',
function (event) {
event.preventDefault();
//event.stopPropagation();
});
});
This fiddle with jQuery 1.6.4 and this with jQuery 1.7.2

I think what this is trying to do is call 'preventDefault' on document, when in reality, you want the 'a' event to be prevented. This is more likely to work:
$('a').on('click', function(e){
e.preventDefault();
e..stopPropagation();
// rest of your stuff
});
if this works as expected, 'stopPropagation' might not even be necessary

Related

Why does my function switching visibility if else statement not work? [duplicate]

I am creating a responsive menu: Codepen Demo
To avoid the page to be reloaded when I click a link I have:
$('nav.menu a[href="#"]').click(function () {
$(this).preventDefault();
});
But this does not seem to work. When I click a button the menu disappears.
Does anyone knows what I am be doing wrong?
It's not the element that need a .preventDefault(), its the click event.
Try this:
$('nav.menu a').click(function (event) {
event.preventDefault();
// or use return false;
});
I don't recommend to use the href as selector though, better to give it an id or name.
From MDN, about .preventDefault():
Cancels the event if it is cancelable, without stopping further propagation of the event.
You can read more here:
MDN: event.preventDefault()
jQuery: Selectors
There is a CSS way, using pointer-events.
So by using in the CSS pointer-events: none; all click will be ignored. This is a "recent" alternative and suported in IE11+, Firefox 3.6+, Chrome 2.0+, Safari 4+.
Example
Here is very easy way to do it inside html.
<a class="font-weight-bold" href="javascript:void(0);"> Click Here </a>
Just return false.
$('nav.menu a[href="#"]').click(function () {
return false
});
Use like that:
$('nav.menu a[href="#"]').click(function (event) {
event.preventDefault();
});
$('nav.menu a[href="#"]').click(function (e) {
e.preventDefault();
});
Try this:
$('.menu a').click(function(e){
e.preventDefault(); // stop the normal href from reloading the page.
});
Working codepen example: http://codepen.io/anon/pen/cynEg
You did not have a reference to the jquery library included. Also the 'enquire' function is now throwing an error but preventDefault is working.
Edit I have commented out the second function.
And an inline option without jQuery:
Link
And don't forget that with this you have already used the "f" name for a function, so don't name other function like this.

How to trigger a anchor tag click event dynamically using javascript?

I'm trying to trigger a already written click event for an anchor tag using JavaScript but it is not working. can any one please help me to do this
I have a anchor tag
<a id="memberid">Data Member</a>
<script>
$("#memberid").click(function() {
changebreadcrumb("Data Management");
});
</script>
i want to trigger above click event on load
i tried
$("#memberid").click();
and
$("#memberid").trigger("click");
but did not work.
Place this at the end of your HTML before the closing body tag
<script>
$(document).ready(function(){
$('#memberid').trigger('click');
});
</script>
DEMO
Use jquery and check whether your dom is ready. It works fine.
See the properties in the fiddle on its left side panel
$("#memberid").click(function() {
alert('clicked');
});
$("#memberid").trigger("click");
EDIT:
FINAL DEMO
If you want to triger click on pageload, use window.onload in javascript or jquery load method as i mentioned.
$(window).load(function()
{
$("#memberid").trigger("click");
});
If your click is not working then in that case....try on() function to trigger event
$(document).ready(function(){
$("#anchor_id").on( "click", function() {
//your work
});
});

Prevent a link to reload page

I am creating a responsive menu: Codepen Demo
To avoid the page to be reloaded when I click a link I have:
$('nav.menu a[href="#"]').click(function () {
$(this).preventDefault();
});
But this does not seem to work. When I click a button the menu disappears.
Does anyone knows what I am be doing wrong?
It's not the element that need a .preventDefault(), its the click event.
Try this:
$('nav.menu a').click(function (event) {
event.preventDefault();
// or use return false;
});
I don't recommend to use the href as selector though, better to give it an id or name.
From MDN, about .preventDefault():
Cancels the event if it is cancelable, without stopping further propagation of the event.
You can read more here:
MDN: event.preventDefault()
jQuery: Selectors
There is a CSS way, using pointer-events.
So by using in the CSS pointer-events: none; all click will be ignored. This is a "recent" alternative and suported in IE11+, Firefox 3.6+, Chrome 2.0+, Safari 4+.
Example
Here is very easy way to do it inside html.
<a class="font-weight-bold" href="javascript:void(0);"> Click Here </a>
Just return false.
$('nav.menu a[href="#"]').click(function () {
return false
});
Use like that:
$('nav.menu a[href="#"]').click(function (event) {
event.preventDefault();
});
$('nav.menu a[href="#"]').click(function (e) {
e.preventDefault();
});
Try this:
$('.menu a').click(function(e){
e.preventDefault(); // stop the normal href from reloading the page.
});
Working codepen example: http://codepen.io/anon/pen/cynEg
You did not have a reference to the jquery library included. Also the 'enquire' function is now throwing an error but preventDefault is working.
Edit I have commented out the second function.
And an inline option without jQuery:
Link
And don't forget that with this you have already used the "f" name for a function, so don't name other function like this.

Good way to keep an anchor tag without default url

In our page we have a slew of anchor tags to which we dynamically attach click handlers. In such a case what is the best way to keep an anchor tag in the mark up?
Currently we have
<a href="javascript:void(0);" >....</a>
We need void value for href as some of them may not get attached with click handlers.
Ommit the href-attribute and when assigning the onclick also set the cursor-style of the elements to "pointer" , otherwise users with JS disabled will be confused when clicking on the elements and nothing happens.
Returning false from a jQuery event handler will prevent the default behavior (and bubbling) for you. There's no need to mess with the href attribute (though that won't hurt).
$(document).on("click", "a.yourSelector", function(){
//your code
return false;
});
Or of course jQuery pre 1.7
$(document).delegate("a.yourSelector", "click", function(){
//your code
return false;
});
For more information on cancelling dom events, see this question (and answer) and this link
The simpler code would be like this:
<a href='#' class='do-stuff'>Link</a>
The "#" sign keeps the html code clean, and readable
jQuery(document).ready(function() {
jQuery(".do-stuff").click(function() {
alert("clicked");
return false; // disables default link action
});
});

Access event to call preventdefault from custom function originating from onclick attribute of tag

I have links like this:
<a href="#" onclick="myfunc({a:1, b:'hi'})" />click</a>
<a href="#" onclick="myfunc({a:3, b:'jo'})" />click</a>
And I would like to do a preventDefault() inside myfunc(), because a # will be added in the address bar when clicking on the link
(without doing return false; or href='javascript:void(0);')
Is this possible?
Can I get the event inside myfunc()
I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).
A quick example.
function sayHi(e) {
e.preventDefault();
alert("hi");
}
Click to say Hi
Run it as is and notice that the link does no redirect to Google after the alert.
Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).
The simplest solution simply is:
<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)
<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' +
Math.round(new Date().getTime() / 1000);"
href="http://www.domain.com/docs/thingy.pdf">
If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.
Try this:
<script>
$("a").click(function(event) {
event.preventDefault();
});
</script>
Can you not just remove the href attribute from the a tag?
<script type="text/javascript">
$('a').click(function(){
return false;
});
<script>
Add a unique class to the links and a javascript that prevents default on links with this class:
<a href="#" class="prevent-default"
onclick="$('.comment .hidden').toggle();">Show comments</a>
<script>
$(document).ready(function(){
$("a.prevent-default").click(function(event) {
event.preventDefault();
});
});
</script>
I think when we use onClick we want to do something different than default. So, for all your links with onClick:
$("a[onClick]").on("click", function(e) {
return e.preventDefault();
});
Simple!
onclick="blabla(); return false"
You can access the event from onclick like this:
<button onclick="yourFunc(event);">go</button>
and at your javascript function, my advice is adding that first line statement as:
function yourFunc(e) {
e = e ? e : event;
}
then use everywhere e as event variable
Without any JS library or jQuery.
To open a nice popup window if possible. Fails safely to normal link open.
...
And the helper function:
function openNewWindow(event, location) {
if (event.preventDefault && event.stopImmediatePropagation) {
event.preventDefault();
event.stopImmediatePropagation();
} else {
event.returnValue = false;
}
window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Or have return false from your method.

Categories

Resources