I am a javascript noob, so apologies if this question is not for this forum. I am trying to understand jQuery method:
e.preventDefault()
In the code below, when moving items form one list to another it is needed for us to be able to move the items. I would like to know what exactly is happening there and what default action are we preventing from happening?
$('#move').click(
function(e) {
$('#list1 > option:selected').appendTo('#list2');
e.preventDefault();
});
$('#moveAll').click(
function(e) {
$('#list1 > option').appendTo('#list2');
e.preventDefault();
});
$('#removeAll').click(
function(e) {
$('#list2 > option').appendTo('#list1');
e.preventDefault();
});
Well basically when you click hyperlink it posts back to url or #
When we add e.preventDefault() function, jQuery will prevent default action of click event.
Therefore when you click #move, page will not refresh but action within function will be executed.
Hope this helps!
It will prevent further default action for current event.
E.g. clicking on link will follow href of element. e.preventDefault(); will prevent following link and you will not be redirected.
More information here
$(document).ready(function() {
$('#a1').click(function(e) {
e.preventDefault();
alert('Clicked, but not following link.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link with preventDefault
<br/>
Link without preventDefault
First of all e.preventDefault() should be first line when defining what all things will happen in function.
$('#move').click(
function(e) {
e.preventDefault();
$('#list1 > option:selected').appendTo('#list2');
});
$('#moveAll').click(
function(e) {
e.preventDefault();
$('#list1 > option').appendTo('#list2');
});
$('#removeAll').click(
function(e) {
e.preventDefault();
$('#list2 > option').appendTo('#list1');
});
Secondly preventDefault prevents the default function of element to which it is applied.
For ex:
<a href="#" class="clickBtn">
If you fire event on above <a> by default it will take to document to top and will show a # in url and then fire you function but if you use preventDefault then its default function of linking will be prevented.
Related
I have a button that's located in an anchor, and that button has some logic that's triggerd by clicking on it.
The problem is that whenever I click on that button, the app get's redirected due the anchor parent element.
<a href="foo" id="bar">
<span id="button">click me</span>
</a>
I tried using .stopPropagation() like it's mentioned in this post, however it doesn't work.
I tried:
$('#button').on('click', function(e) {
e.stopPropagation();
})
Here's the fiddle.
However, if I replace the parent anchor with a div, then it works - JSFiddle
Am I doing something wrong?
Update: I know I can prevent redirecting with e.preventDefault(), however, I want when I click on the parent element to redirect, and when I click on the button not to redirect and start doing my JS functions (open modal).
Try this:
$('#bar').on('click', function(e) {
if( $(e.target).is('#button') ) {
e.preventDefault();
//your logic for the button comes here
}
//Everything else within the ancho will cause redirection***
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="foo" id="bar">OK
<span id="button">click me</span>
</a>
Try:
e.preventDefault();
Fiddle: http://jsfiddle.net/hfyy10a8/3/
You should use e.preventDefault(); on links:
$('#bar').on('click', function(e) {
e.preventDefault();
});
You can also add it on your example, all together:
$('#button').on('click', function(e) {
e.stopPropagation();
e.preventDefault();
});
use return false:
$('#button').on('click', function (e) {
//some logic
$(this).css('color', 'red');
return false;
});
The reason why stopPropagation wont work is because it will prevent event handlers from running, not native behavior.
Try to use e.preventDefault() instead:
$('#button').on('click', function (e) {
e.preventDefault();
});
See this explanation for why e.stopPropagation() is not working.
I know this question already has an answer but however, I made mine work by returning false on the "onclick" attribute of the child element.
<a href="https://google.com">
<button onclick="return doTask()">Do not navigate</button>
</a>
function doTask(){
//... write action
return false; <- This prevents the click action from bubbling up to parent tag
}
I have some lis including a links as below
<li>
<span>SomeText</span>
<a href='someurl' class='entityDetailModal'>sometext</a>
</li>
I am using a third party library ('LightGallery') that adds click event on Li, and by Jquery I have add click event to the links to show a dialog.
The problem is when I click on link both click event will be fired,
my click event handler is
$('body').on("click", 'a.entityDetailModal', function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
I tried event.stopPropagation() and event.preventDefault(); and return false; in link onclick event handler but they don't work.
Sample:http://jsfiddle.net/HuKab/30/
How can I overcome this?
Update
It seems the problem is the way I add click event handler,
using this way it seems that everything is ok
$('a.entityDetailModal').click(function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
Update 2
Thanks #Huangism, this post stackoverflow.com/questions/16492254/pros-and-cons-of-using-e-stoppropagation-to-prevent-event-bubbling is explaining the reason.
Use stopPropagation(); in child element
$("li").click(function (e) {
alert("li");
});
$("a").click(function (e) {
e.preventDefault(); // stop the default action if u need
e.stopPropagation();
alert("a");
});
DEMO
It is not very clear to me what your problem really is. If you simply want to get rid of the click on the li tag you may use .unbind() from jQuery (see: http://api.jquery.com/unbind/). You should end up with only your click event.
Another thing that might help is to use something like:
$("a").on('click.myContext', function(event) {
//Your action goes here
}
This way you can have parallel events and turn them on with $("a").on('click.myContext') and off with $("a").off('click.myContext')
Edit: Use:
$("a").on('click.myContext',function (e) {
e.stopPropagation();
alert("a");
});
see working example: http://jsfiddle.net/bGBLz/4/
I'm trying to change the data-url with jQuery. Currently my code looks like this.
<div id="twitterButton" title="Tweet it on Twitter">Tweet</div>
<script type="text/javascript">
$(document).ready(function () {
$('#twitterButton').click(function () {
$('#tweet').attr("data-url", "https://www.google.com/");
});
});</script>
As you can see I left the url-data blank so I could be sure it is only getting set in the jQuery. However whenever I click the tweet button it always opens the window with the link for the current page that I was on. Can someone explain how I can set it to be something else via jQuery or javascript?
You should use .data() for controlling data attributes. As Daniele states in that answer, you must also stop the event propogation on the a element using preventDefault().
$('#twitterButton').click(function (e) {
$('#tweet').data('url',"https://www.google.com");
e.preventDefault();
});
You must call the preventDefault() method to stop the propagation of the click event on the child a element:
Try this code:
$('#twitterButton').click(function (e) {
$('#tweet').attr("data-url", "https://www.google.com/");
e.preventDefault();
});
Good code
D.
I have a link that looks like this:
<a href="page.html" class="myLink">
Link text
<div class="toggle">x</div>
</a>
When they click on the x in toggle I want to prevent the link from navigating, but if they do click on the Link Text I want the link to navigate.
I tried this:
$('.toggle').click(function(event) { $(this).parents('a').preventDefault(); });
But it didn't seem to work.
To stop propagation from the clicked element to the outer a, you'd have to call stopPropagation. But here you can simply return false ( which both stops propagation and prevents default behavior) :
$('.toggle').click(function(event) {
// do interesting things
return false
});
It is the event not the element that you need to fire the preventDefault() method upon.
$('.toggle').click(function (event) {
event.preventDefault();
});
This will stop the event from triggering but not propagating up the document.
$('.toggle').click(function (event) {
event.stopPropagation();
});
Is it's counterpart.
I am trying to override the default behaviour of an anchor tag so i can load in a web page on my server into the exisiting div, rather than a new tab or window.
so far i have:
myContainer.click(function(){
event.preventDefault();
$('a').click(function(){
var link = $(this).attr('href');
myContainer.load(link);
});
});
In chrome i have to click the link twice before it does anything, in IE an FF it doesnt work at all and refreshes the page with the new link.
Any help is much appreciated.
Shouldn't it be just:
$('a').click(function(e) {
e.preventDefault();
myContainer.load(this.href);
});
Your code assigns a click handler inside a click handler. So the first click will attach the click handler to the link, and the second click (on the link) will execute the new click handler.
It seems you only need one click handler. If the links are added dynamically, you can use .on() (the successor of .live and .delegate):
myContainer.on('click', 'a', function(e) {
e.preventDefault();
myContainer.load(this.href);
});
// or
$(document).on('click', 'a', function(e) {
e.preventDefault();
myContainer.load(this.href);
});
you forgot to pass in event:
myContainer.click(function(event){
event.preventDefault();
$('a').click(function(){ var link = $(this).attr('href');
myContainer.load(link);
});
});
try to rearrange them:
myContainer.ready(function(){
$('a').click(function(event){
event.preventDefault();
var link = $(this).attr('href');
myContainer.load(link);
});
});