How to bind a .click() event only the container? - javascript

I want the user entry to open up accordion-style, but a .click() event is triggered even if I click on any other element inside the red box - the text, the image, etc.
I'd like to only have the "outer" whitespace cause the event to trigger.
How do I accomplish this?
$('#box').click(function(e) {
console.log(e);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" style="width:80%;background:red;">
<table>
<tr>
<td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td>
<td><b>John McDerpenstein</b></td>
<td><p>
A blurb goes here
</p></td>
</tr>
</table>
</div>
fiddle

You can check the target property of the event to see if it was the #box element directly by using is():
$('#box').click(function(e) {
if ($(this).is(e.target))
console.log(e);
});
Updated fiddle

<html>
<body>
<div id="box" style="width:80%;background:red;">
<table>
<tr>
<td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td>
<td><b>John McDerpenstein</b></td>
<td><p>
A blurb goes here
</p></td>
</tr>
</table>
</div>
<script src="jquery-1.12.3.min.js"></script>
<script>
$('img').click(function(e) {
console.log(e);
});
</script>
</html>

Just check the e.target.id to see if it matches the specific id of the outer box you want. Example below:
$('#box').click(function(e) {
if (e.target.id === "box")
console.log('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" style="width:80%;background:red;">this is the outer box
<table>
<tr>
<td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td>
<td><b>John McDerpenstein</b></td>
<td><p>
A blurb goes here
</p></td>
</tr>
</table>
</div>

If you want to add the event to the parent container you will have to stop the propagation on all the child elements that will not need a click event .
Example :
since #box has the click and box is your container
you will need to give image an id and stop the propagation
$('#imageID').click(function(e){
e.stopPropagation();
})
With the example above when you click the image nothing will happen , but if you click the red container then your event will log.

The best way is to prevent the event if the click is done on child:
$('#box').click(function(e) {
if (!$(this).is(e.target)) {
return e.preventDefault()
}
// code here (or nothing, href="" action)
});

Related

Stop Propagation not working

I'm trying to stop the bubbling of event of an inner checkbox to the click event of the tr element.
I have the following mark up:
<table border="1">
<tr class="row">
<td>
Item 1
</td>
<td>
<input type="checkbox" class="cb">
</td>
</tr>
<tr class="row">
<td>
Item 2
</td>
<td>
<input type="checkbox" class="cb">
</td>
</tr>
</table>
The rows are dynamically added, so to add listeners automatically to dynamically added elements, I used the following code:
$(document).ready(function() {
$('body').off('click.row').on('click.row', '.row', function() {
alert(1);
});
$('body').off('change.cb').on('change.cb', '.cb', function(e) {
e.stopPropagation();
alert(2);
});
});
However the event still bubble up to the tr element. I tried also the following:
e.stopImmediatePropagation();
window.event.cancelBubbles = true;
e.bubbles = false;
none seemed to work.
I reproduced this issue with JSFiddle:
JSFiddle
In this case, there is no event bubbling occuring because you have different events defined on different elements that just so happen to both fire when a mouse clicks on the check box (because you have also clicked a row).
You should either not add the row click event listener at all, or move stopPropagation to the the other handler to stop it from firing.
$(document).ready(function() {
$('body').off('click.row').on('click.row', '.row', function() {
e.stopPropagation();
alert(1);
});
$('body').off('change.cb').on('change.cb', '.cb', function(e) {
alert(2);
});
});

how to show edit button upon right click on table row

Is it possible that i can show edit button after right clicking on row of a table? I wanted to inbuilt this functionality in my html page but i am not getting the idea how to do that. MY html page is like this
<table class="table table-hover table-bordered" id="tblData">
<thead>
<tr>
<th>Parameter Names</th>
<th>Parameter Values</th>
<th>Remarks</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>johnrambo#mail.com</td>
<td>John</td>
<td>Rambo</td>
<td>
<a class="btn btn-mini btnEdit">Edit</a>
</td>
</tr>
<tr>
<td>peterparker#mail.com</td>
<td>Peter</td>
<td>Parker</td>
<td>
<a class="btn btn-mini btnEdit">Edit</a>
</td>
</tr>
</tbody>
</table>
When i right click on the row of this table then it should show me edit buttin which i can use to edit the table. TO edit the table i have js file but that is other thing. Main thing I want to make the edit button visible after right click.And also I have use bootstrap to improve the visibility. Please help me to solve this problem.
This code might help you:
on right clicking on specific <tr>
1) no default browser menu opens
2) Show/hide edit link
On clicking on document (both left and right)
1) hide edit link (can be changed accordingly)
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
.btnEdit{display:none;}
</style>
</head>
<body>
<table class="table table-hover table-bordered" id="tblData">
<thead>
<tr class ='abc' >
<th>Parameter Names</th>
<th>Parameter Values</th>
<th>Remarks</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id = 'John1' class ='abc'> <!-- id=username+userid -->
<td>johnrambo#mail.com</td>
<td>John</td>
<td>Rambo</td>
<td>
<a class="btn btn-mini btnEdit" href='asd.html' >Edit</a>
</td>
</tr>
<tr id = 'Peter1' class ='abc'>
<td>peterparker#mail.com</td>
<td>Peter</td>
<td>Parker</td>
<td>
<a class="btn btn-mini btnEdit" id ="btnEdit" href='asd.html' >Edit</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function(){
$('.abc').contextmenu(function(){
$('.btnEdit').hide();
var id = $(this).attr('id');
$('#'+id+' .btnEdit').toggle();
return false;
});
$(document).click(function(){
$('.btnEdit').hide();
});
});
</script>
try it here http://jsfiddle.net/f5n9f4po/2/
The event you're looking to capture is window.oncontextmenu. I'm pretty sure you can tie the event to right click by binding it to the tr tags.
(tr selector).oncontextmenu = function () {
toggleEditButton() // callback fn for showing your edit button
return false; // Prevents actual right click menu from showing up
};
Refer to this for more info.
You can handle it using onmousedown event. When you press the mouse button this event will be fired and by checking it's keyCode you can find if it's the right mouse button.
This should serve your purpose.
HTML :
<div onmousedown="showEditButton(event);">Row Content</div>
<button id="editButton" style="display:none;">Edit</button>
javaScript :
function showEditButton(event){
event = event || window.event;
if(event.which == 3){
var button = document.getElementById("editButton");
button.style.display = 'block';
}
}
jsFiddle - javaScript
jQuery :
$("#editableContent").mousedown(function(event){
if(event.which == 3){
$("#editButton").show();
}
});
jsFiddle - jQuery
Resources :
onmousedown , .mouseDown() , event.which
This answer is based on Making custom right-click context menus for my web-app implemented to work for your situation.
JSFiddle
Here's the JQuery:
// Trigger action when the contexmenu is about to be shown
$('.btnEdit').bind("contextmenu", function (event) {
// Avoid the real one
event.preventDefault();
// Show contextmenu
$(".custom-menu").finish().toggle(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
});
// If the document is clicked somewhere
$(document).bind("mousedown", function (e) {
// If the clicked element is not the menu
if (!$(e.target).parents(".custom-menu").length > 0) {
// Hide it
$(".custom-menu").hide();
}
});
// If the menu element is clicked
$(".custom-menu li").click(function () {
// This is the triggered action name
switch ($(this).attr("data-action")) {
// A case for each action. Your actions here
case "edit":
alert("Edited!");
break;
}
// Hide it AFTER the action was triggered
$(".custom-menu").hide();
});

Jquery will not remove div

I have form in which I am adding some dynamic actions. I have a table in which I have rows of positions
applicants applied for. There is an offer postion button and when they click on the offer button I want to insert the offer fields to be submitted and updated. I can get the feilds to insert but when I click on the cancel transaction button, I can't get it to empty the div addapptrans where the form is built. Below is the code. I know it must be something simple I am missing.
<head>
<script type="text/javascript">
$(function(){
$(".offerposition").click(function(){
var row = $(this).closest('tr').find('td:nth-child(1)').text();
alert('You clicked on ' +row);
$("#addapptrans").empty();
$("#addapptrans").append(
$("<input>").attr('type','hidden').attr( 'value',row).attr('Name','Mchposid'))
.append(
$("<input>").attr('type','submit').attr( 'value','Complete Offer').attr('id','completeoffertrx').attr('name','completeoffertrx').addClass("buttonlarge buttonmargin")
).append(
$("<input>").attr('type','button').attr( 'value','Cancel Transaction').attr('id','canceloffertrx').attr('name','canceloffertrx').addClass("buttonlarge buttonmargin")
);
}
)
}
);
$(function(){
$("#canceloffertrx").click(function(){
$("#addapptrans").empty();
})
})
</script>
</head>
<body>
<form >
<div id="addapptrans"></div>
<p class="posttitle">Positions applied For</p>
<table class="tabpositions">
<tbody>
<tr>
<th class="position">Position</th>
<th class="department">Department</th>
<th class="dateapp">Date Applied</th>
<th class="appdate">Offer?</th>
</tr>
<tr>
<td style="display: none;">2281</td>
<td>Building Service Worker - Part time</td>
<td>Environmental Services</td>
<td>08/13/2001</td>
<td><input type="button" class="offerposition" value="Offer Position"></td>
</tr>
</tbody>
</table>
</form>
This code here:
$(function(){
$("#canceloffertrx").click(function(){
$("#addapptrans").empty();
})
})
Runs before #canceloffertrx exists on the page. So $("#canceloffertrx").click(fn) Matches zero elements on the page, and binds a click handler to all zero of them.
You can fix this by binding the click handler to the document, or closest parent that is present, instead.
$('#addapptrans').on('click', '#canceloffertrx', function(){
This says that when the element #addapptrans receives a click event, and element that matches the selector #canceloffertrx was the one that was actually clicked, fire the event handler function.
Or by binding the click handler when you create the button.
$("<input>")
.attr('type','submit')
.attr( 'value','Complete Offer')
.attr('id','completeoffertrx')
.attr('name','completeoffertrx')
.addClass("buttonlarge buttonmargin")
.click(function() { ... });
Lastly, some style advice :) Especially when chaining jQuery methods, you can put each call on it's own line which makes it much more readable.
And you should also know that attr() can accept an object as an argument, allowing to call it just once to set many attributes.
$("<input>")
.attr({
type: 'submit',
value: 'Complete Offer',
id: 'completeoffertrx',
name: 'completeoffertrx'
})
.addClass("buttonlarge buttonmargin")
.click(function() { ... });

Using mouseover and mouseout in a element makes a hover blinking continuously

I am rendering two elements on a JSP page dynamically, with dynamic IDs. On mouse over of each element I am rendering a div, and on mouse out I am making the same display value none. The issue is when I hover on the div, the div is keeping on blinking. How can I solve this?
Example code:
<table>
<tr>
<td>
<div onmouseover="showblock(hoverdivid)" onmouseout="hideblock(hoverdivid)">india</div>
<div class="hoverdiv" id="dynamicallygenerated">
<li>a list of checkboxes with state names of the country hovered will be inserted using ajax</li>
</div>
</td>
<td>
<div onmouseover="" onmouseout="">america</div>
<div class="hoverdiv" id="dynamicallygenerated">
<li>a list of checkboxes with state names of the country hovered will be inserted using ajax</li>
</div>
</td>
</tr>
</table>
<script>
var showblock;
var hideblock;
$(document).ready(function (e) {
showblock = function (id) {
$("#" + id).show();
}
hideblock = function (id) {
$("#" + id).hide();
}
});
</script>
Extending my question
i mentioned that am inserting checkboxes in the hover using ajax, in the same hover i have an add button which adds the values that i checked in the hover to some other div outside the table. i have two countries so two hovers with their cites so when i checked and click on add the values of two hovers to be displayed which are checked should display individually suggest me the approach to follow to solve the above requirement
This is happening because when the hoverdiv is shown your mouse is on it thus the mouseleave event is triggered so the hoverdiv disappears and then your mouse is on the first div again so the mouseenter event is triggered so hoverdiv appears again.... and so on.. this causes the flickering
My best suggestion will be to nest the hoverdiv: (You'll have to tweak the css a bit)
<table>
<tr>
<td>
<div onmouseover="" onmouseout="">
india
<div class="hoverdiv"></div>
</div>
</td>
<td>
<div onmouseover="" onmouseout="">
america
<div class="hoverdiv"></div>
</div>
</td>
</tr>
</table>
When the hoverdiv is inside the other div, mouseleave will not be triggered when you hover the hoverdiv
Working Demo http://jsfiddle.net/cse_tushar/FKacT/1
HTML
<table border="1">
<tr>
<td>
<div class="div">india</div>
<div class="hoverdiv" id="dynamicallygenerated">
<li>a list of checkboxes with state names of the country hovered will be inserted using ajax</li>
</div>
</td>
<td>
<div class="div">america</div>
<div class="hoverdiv" id="dynamicallygenerated">
<li>a list of checkboxes with state names of the country hovered will be inserted using ajax</li>
</div>
</td>
</tr>
</table>
css
td{
vertical-align: top;
}
js
$(document).ready(function () {
$('.div').hover(function () {
x = $(this).css('width');
$(this).parent().find('.hoverdiv').show();
$(this).css('width', $(this).parent('td').width());
}, function () {
$(this).css('width', x);
$(this).parent().find('.hoverdiv').hide();
});
});

jquery/jqueryui, click anywhere in div besides button

I have a div as a ui-widget-content with a h3 as a ui-widget-header. The header has three buttons. Each have the class "save" "delete" and "cancel" respectivly. I want to have a .click function whene ever you click on the div, except if you actually click on one of the buttons.
I tried: $(".record").not(".save").not(".delete").not(".cancel").click(
my code is:
<div class="record cursorPointer hoverClass ui-widget-content">
<h3 class="ui-widget-header">
<table width="100%"><tr>
<td align="left" style="width:33%; color:Red">somecontractorone</td>
<td style="width:33%" align="center"> Name: Joe Q Shmoe </td>
<td style="width:33%" align="right"> Buisness: joeqshmoeelectrical</td>
<td><button style="width:20px;height:20px" class="save"></button></td>
<td><button style="width:20px;height:20px" class="delete"></button></td>
<td><button style="width:20px;height:20px" class="cancel"></button></td></tr>
</table>
</h3>
</div>
However the click function still activated when clicking the buttons.
Any ideas?
You can use the event.target to see what was clicked. Then rely on even bubbling and attach the click handler on the parent div. jsfiddle
$('.record').click(function(e){
if($(e.target).is(':button'))
alert('button');
else
alert('not button');
});
Assuming that you have another event handler (or several) that handles the buttons, you can prevent the bubbling there with
$('button').click(function(e) {
e.stopPropagation();
switch( this.className ) {
// Or whatever...
}
})
Use e.stopPropagation() in the buttons' click handler(s):
$('button').click(function(e) {
e.stopPropagation();
alert('you clicked a button!');
});
Here's a demo: http://jsfiddle.net/Ender/2yERz/
And some documentation on e.stopPropagation(): http://www.quirksmode.org/js/events_order.html#link9

Categories

Resources