jquery on() method doesnt work with td child? [duplicate] - html

I have the following markup
<ol>
<li class="ListItem">
<span class="sub">#qItem.CategoryText</span>
<input type="image" src="http://icons.iconarchive.com/icons/tatice/just-bins/256/bin-red-full-icon.png" width="30" class="deleteIcon" name="QuestionId" value="#qItem.Id" />
</li>
</ol>
and the following script
$(".ListItem").click(function(){
doActionA();
});
$(".deleteIcon").click(function(){
doActionB();
});
When I click in image, it also triggers click of ListItem. I understand this is because image is inside ListItem. but I want ListItem's click not to be fired when image is clicked.
Is there any way to do that ?

$(".deleteIcon").click(function(e){
doActionB();
e.stopPropagation();
});

You need to use event.stopPropagation() to prevents the event from bubbling up the DOM tree.
$(".deleteIcon").click(function(event){
event.stopPropagation()
doActionA();
});
The event you binded with delete icon is firing the parent event binding with ListItem, so you need to stop propagation for parent event when child is source of event.

$(document).on("click", ".deleteIcon", function() {
doActionB();
});
This method is the only one I found to work with nested elements, especially those generated by a library such as Pivottable (https://github.com/nicolaskruchten/pivottable)

$(".deleteIcon").click(function(){
doActionA();
return false;
});

Use .one(), as directed in the JQuery documentation.

Related

How to disable and then re-enable onclick event in <img> using jquery

I have used an image instead of button, now I want to disable the onclick() event in some case as we disable a button. I tried many ways but doesn't work. Below is what I did:
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
The jQuery code is:
$("#upd_1").css('opacity','0.5');
$("#upd_1").unbind("click");
I also tried:
$("#upd_1").css('pointer-events','none'); and document.getElementById('upd_1').style.pointerEvents = 'none';.
Any solution?
Try this:
$("#upd_1").on('click',function(e){
e.preventDefault();
});
One hint is that you can give your click event a suffix so you can be sure it's the only event you are affecting. To bind:
$('#elementId').on('click.myevent', function () {
// your code
}
To unbind:
$('#elementId').off('click.myevent');
Not going into binding or unbinding the click event but how about creating a mask for the image. Hide the mask when you want the image to be clickable else show it.
img onclick="alert('clicked')" src="http://lh3.googleusercontent.com/mjejVTJKT4ABNKq2HGlkDs36f-QvzI2hKFER098vBIgiAoZ2H-SN5QPvFaZEVDZRxfujrS6pszZ_J-_di2F57w0IFE3KAciDwGAh-9RcCA=s660" alt="" />
<div id="mask"></div>
<script>
$('#mask').hide();
$('#disable').click(function() {
$('#mask').show();
});
$('#enable').click(function() {
$('#mask').hide();
});
</script>
Try the Plnkr: Plnkr
Try this way. Add your parameters in two attributes (data-a and data-b for example).
<img title="Ok" class="mtbtn"id="upd_1" data-a="1" data-b="MM" src="/project/images/green_ok.gif" border="0">
Then change your javascript in this way:
$(document).ready(function(){
$("#upd_1").bind("click", function(){
var a = $(this).data("a");
var b = $(this).data("b");
// Code here
$(this).unbind("click");
});
});
Here the result.
Alternative is this:
var semaphore = true;
function add_edited (a, b) {
if (semaphore) {
semaphore = false;
// Code here
}
}
Create a semaphore to manage the execution of the code to the click.
i understood you'r problem, there is no need to unbind() and re bind() the onclick event, you can simply remove and re-add onclick attribute using removeAttr() and attr()
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
JQuery:
$("#upd_1").css('opacity','0.5');
$("#upd_1").removeAttr('onclick');
to re add onclick event do the following:
$("#upd_1").css('opacity','1');
$("#upd_1").attr("onclick","add_edited('1','MM');");
that is all you need to do.

Disabled button is clickable on Edge browser

I have problem with Edge browser. In my web site I have buttons with span tags inside them. In this span tags I bind text and icons. So far I had no problem but on Edge browser it is possible to click on disabled buttons. After investigating problem I found out that, when button contains span tags inside, it is possible to click on button. Here is how it looks on my web site:
<button id="btnRefresh" type="button" class="btn btn-primary" ng-click="refresh()" ng-disabled="performingAction">
<span ng-class="performingAction && action == 'refresh' ? 'fa fa-cog fa-spin' :'fa fa-refresh'"></span>
<span>{{ refresh }}</span>
</button>
Here is example to testing:
<button type="button" disabled="disabled" onclick='alert("test");'>
<span>Click me!</span>
</button>
One option would be to hide buttons instead of disabling, but I prefer to disable them. Please suggest solution to over come this issue.
Just set
pointer-events: none;
for disabled buttons.
Here's CSS to disable all disabled elements everywhere:
*[disabled] {
pointer-events: none !important;
}
pointer-events documentation
This is a bug in Microsoft Edge. Disabled buttons accept clicks if they contain any HTML elements (i.e. if they contain anything else than just text).
Reported multiple times via Microsoft Connect:
Event bubbles from child element into element (by SO user Ryan Joy)
Bootstrap/Jquery disabled buttons generate click events and show tooltips even disabled
The bug was still present in Build 10565 (16 October 2015).
It was fixed in the November update, Build 10586.
A possible (but ugly) workaround is to call some Javascript in onclick for every button, which then checks if the button is disabled and returns false (thus suppressing the click event).
One work around I've come up with using angularjs is inspired by Ben Nadel's blog here
So for example:
angular.module('myModule').directive(
"span",
function spanDirective() {
return ({
link: function (scope, element, attributes) {
element.bind('click', function (e) {
if (e.target.parentNode.parentNode.disabled || e.target.parentNode.disabled) {
e.stopPropagation();
}
})
},
restrict: "E",
});
}
);
Since you're not always going to be using a span element and probably don't want to create a new directive for every element type, a more general workaround would be to decorate the ngClick directive to prevent the event from reaching the real ngClick's internal event handler when the event is fired on a disabled element.
var yourAppModule = angular.module('myApp');
// ...
yourAppModule.config(['$provide', function($provide) {
$provide.decorator('ngClickDirective', ['$delegate', '$window', function($delegate, $window) {
var isEdge = /windows.+edge\//i.test($window.navigator.userAgent);
if (isEdge) {
var directiveConfig = $delegate[0];
var originalCompileFn = directiveConfig.compile;
directiveConfig.compile = function() {
var origLinkFn = originalCompileFn.apply(directiveConfig, arguments);
// Register a click event handler that will execute before the one the original link
// function registers so we can stop the event.
return function linkFn(scope, element) {
element.on('click', function(event) {
if (event.currentTarget && event.currentTarget.disabled) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
});
return origLinkFn.apply(null, arguments);
};
};
}
return $delegate;
}]);
}]);

Hover not working on AJAX

I have the below content that loads on through AJAX.
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg">
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"> <i class="icon-film icon-white"></i>
Genre
</p>
</div>
</div>
</div>
Additionally, I have writen the following script in jquery that applies to the above 'div.grid'.
jQuery(function ($) {
$(document).ready(function () {
$(".grid").on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
});
The script works fine when the page loads the first time. However, the hover effect doesn't work once the above div is generated via AJAX after clicking on an 'a' tag. I can't seem to figure out what's wrong here? New to all this. Can anyone help?
To append these event handlers to dynamically generated elements, you need to bind to the document or another static parent element and then specify .grid as the second argument passed to .on.
The second argument is used as a filter to determine the selected elements that trigger the event. So when the event is fired it will propagate to the document or parent element selected by jquery. The event target will then be scrutinized using the selector provided as the second argument. If the target matches the second argument, (.grid in our case), the event is fired.
You can read more in the jQuery documentation.
Also, since your using document.ready there is no need for the short hand ready statement, jquery(function($).
$(document).ready(function () {
$(document).on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
}, ".grid");
});
you lost your binding because of ajax that overwrite your div with class=".grid"
use parent element for binding
$('.ParentElementClass').on("mouseleave", ".grid", function(){...})
more from jquery api
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Not sure what you're shooting for here but a little malformed HTML may have done it...
jsFiddle Demo
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg" />
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"><i class="icon-film icon-white"></i>Genre</p>
</div>
</div>
</div>
$(function () {
$(".grid").on({
mouseenter: function () {
alert('entered');
$(this).find('.meta').stop().animate({
bottom: '0px'
}, 200);
},
mouseleave: function () {
alert('left');
$(this).find('.meta').stop().animate({
bottom: '-75px'
}, 200);
}
}, ".thumb");
});
});
Be sure to close img tags. They're notorious for causing intermittent glitches.
You can just use the hover function:
jQuery(function ($) {
$(document).ready(function () {
$(".grid").hover(function () { /*mouseenter*/
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},function(){ /*mouseleave*/
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
Explanation:
The first parameter function does the work of mouseenter and the second does the work of mouseleave.
I'd recommend using those both, mouseenter and mouseleave in situation when you don't want an effect back when the user gets off his mouse from the element.

unable to attach click event to li element using jquery

I am unable to get the click event for this HTML:
<ul id="frd_overlay_list">
<li><div class="divLink"><div id="1"><img src="path"><div class="frdName">Name</div></div></div></li>
<li><div class="divLink"><div id="2"><img src="path"><div class="frdName">Name</div></div></div></li>
</ul>
and JQuery script:
$('li').click(function(){
console.log('Not working');
});
I am able to get click event for the ul element i.e.
$('ul#frd_overlay_list').click(function(){
console.log('This works');
});
I have tried this, but this also doesnt work:
$('ul#frd_overlay_list li').click(function(){
console.log('Doesn't work either');
});
Please give me pointers what am I doing wrong?
All your example works except for the last one:
You need to escape the ' or use double quotes for the string
$('ul#frd_overlay_list li').click(function(){
console.log("Doesn't work either");
});
Since you want to apply the click events for dynamically added elements, you could use on function of jQuery.
on would bind event handlers for dynamically added elements
bind would only bind event handlers for currently existing elements.
Usage of on:
$("ul#frd_overlay_list li").on("click", function(){
console.log("Doesn't work either");
});
Fiddle

Prevent page from going to the top when clicking a link

How can I prevent the page from "jumping up" each time I click a link? E.g I have a link somewhere in the middle of the page and when I click it the page jumps up to the top.
Is the anchor href="#"? You can set it to href="javascript:void(0);" instead.
If you are going to a prevent default please use this one instead:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
Let's presume that this is your HTML for the link:
Some link goes somewhere...
If you're using jQuery, try like this:
$(document).ready(function() {
$('a#some_id').click(function(e) {
e.preventDefault();
return false;
});
});
Demo on: http://jsfiddle.net/V7thw/
If you're not on jQuery drugs, try with this pure DOM JavaScript:
window.onload = function() {
if(document.readyState === 'complete') {
document.getElementById('some_id').onclick = function(e) {
e.preventDefault();
return false;
};
}
};
It will jump to the top if you set the link href property to # since it is looking for an anchor tag. Just leave off the href property and it won't go anywhere but it also won't look like a link anymore (and make sure to handle the click even in javascript or else it really won't be of much use).
The other option is to handle the click in javascript and inside your event handler, cancel the default action and return false.
e.preventDefault();
return false;