jQuery - who really clicked me? - javascript

I have this jsbin ( prev answers didn't help much)
 
<span id="mySpan" > click here </span>
  <br/> 
  <input id="myCb" type="checkbox"/>
i have a listener for checkbox click which do Alert...
However , clicking on the span is triggering the click event for the checkbox.
I want to detect - who really made the checkBox execute the alert.
But !
I want :
if first clicked the span , alert
i was originally pressed by mySpan
else
if first clicked the checkbox , alert i was originally pressed by myCb
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger('click');
});
$("#myCb").on('click',function (e)
{
doWork(e)
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
}
p.s. i can use a global field or flag solution - which i DONT WANT.
i will be glad to have a "moving the data" through the e param - solution.
thanks.:)
edit
jQuery does support moving data , but i cant write the right code

This works for me,
<html>
<head>
<style>
</style>
<script src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$("#mySpan").on('click',function (e){
$("#myCb").trigger('click','span');
});
$("#myCb").on('click',function (e,span){
var ele = span || 'cb';
doWork(ele);
});
function doWork(ele){
alert('i was originally pressed by ' + ele );
}
})
</script>
</head>
<body>
<span id="mySpan" style="width:100px;height:100px;" > click here </span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</body>
</html>
Fiddle

how about this.
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger(e);
});
$("#myCb").on('click',function (e)
{
doWork(e);
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.target).attr('id') );
}
It worked for me and it was the closest to your original code.
in action http://jsbin.com/ixanup/2/edit#javascript,html

$("#mySpan, #myCb").on('click', function (e) {
alert('I was originally pressed by ' + e.target.id);
console.log($(e.target)); /* jQuery reference to the clicked element */
if (e.target.id === 'myCb') {
/* do code only if checkbox was clicked */
}
});
Example fiddle: http://jsfiddle.net/4AVZz/

maybe this code helpful for you:
$("#mySpan").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
if($("#myCb").attr('checked')=="checked")
$("#myCb").removeAttr('checked');
else
$("#myCb").attr('checked','checked');
});
$("#myCb").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
});

$("#mySpan").on('click',function () {
var cb = $("#myCb");
if(cb.is(':checked')) {
cb.removeAttr('checked');
} else {
cb.attr('checked', true);
}
doWork.apply($(this));
});
$("#myCb").on('click',function (e) {
doWork.apply($(this));
});
function doWork(e) {
console.log('i was originally pressed by '+$(this).attr('id') );
alert('i was originally pressed by '+$(this).attr('id') );
}
I've modified your example as per your requirement. And saved as a new version.
Please have a look at this. http://jsbin.com/axaqer/7/edit

I would do something like this:
$(function() {
$('.row span, .row input[type="checkbox"]')
.on('click', function (evt) {
triggerCheckbox($(this), evt.currentTarget.tagName);
doWork(evt.currentTarget.tagName);
});
});
function doWork(elm) {
// elm with either be INPUT or SPAN
console.log('I was originally pressed by ' + elm);
}
function triggerCheckbox(elm, evt) {
// if it's a SPAN, let's change the checkbox value without
// triggering the click event
if(evt.currentTarget.tagName === 'SPAN') {
var ckb = $(elm).closest('.row').find('input[type="checkbox"]');
$(ckb).prop('checked', !$(ckb).prop('checked'));
}
}
and it will not matter what ID you have, it will work with all, as long as you have a wrapper grouping the both.
in HTML, I added a <div> to wrap your content, so it will look like:
<div class="row">
<span id="mySpan">click here</span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</div>
live example can be found on JsBin as well.

why dont you use,
e.currentTarget
?

Related

How can I Identify the DIv which got clicked in Jquery

I need to know where the click event happens in my document, i Have some divs , and when i press cntrl key and click on them some events will occur, i just need to know how to identify the divs which got clicked, is it possible to generalize them in document.click fn Like what i have tried.
Here is a sample of what i have tried
HTML
<div class="DivOne">Div1</div>
<div class="DivTwo">Div2</div>
<div class="DivThree">Div3</div>
Jquery
$(document).bind("click", function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
You can use e.target along with .is() function to achieve what you want.
Try,
$(document).bind("click", function (e) {
if($(e.target).is('.DivOne')){
alert('Div one has been clicked..!')
}
});
$("div").click(function (e) {
var classOfDiv = this.className;
// do stuff depending on what class
});
You can select classes, or ids like so
$("#DivOne").click(function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
or a class like
$(".DivOne").click(function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
Alternately you can loop through all divs on the page and test for a click
$("div").each(function () {
$(this).click(function() {
var divClass = $(this).attr('class');
alert("You clicked on " + divClass);
});
});
Fiddle

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

If jQuery has Class do this action

I am trying to check whether or not a particular element has been clicked but am having trouble doing so. Here is my HTML:
<div id="my_special_id" class="switch switch-small has-switch" data-on="success" data-off="danger">
<div class="switch-on switch-animate"><input type="checkbox" checked="" class="toggle">
<span class="switch-left switch-small switch-success">ON</span>
<label class="switch-small"> </label>
<span class="switch-right switch-small switch-danger">OFF</span>
</div>
</div>
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
</script>
I am guessing that my id "my_special_id" is not what is actually being clicked?
I guess click event should have event parameter.
$(document).ready(function() {
$('#my_special_id').click(function(e) {
if (e.target check condition) {
window.alert('ON!');
}
});
});
parameter 'e' above specified is the event object that has all info about click event.
so if u check all info under 'e.tartget', u will be able to find out which one is clicked.
Hope it's helpful for you.
Cheers :)
Since you are looking for a alert when the checkbox is clicked
$(document).ready(function() {
$('#my_special_id input.toggle').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
Demo: Fiddle
Simply put alert when you click on that particular class switch-on
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id div:first-child .switch-on').on('click',function() {
window.alert('ON!');
});
});
</script>
Or even try like
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($(this + 'div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
This JavaScript works for me.
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
alert("On!");
}
});
});
You are sure you have JQuery?
Your code looks fine I think either you have a syntax error somewhere else or you do not have JQuert.
does this alert?
$(document).ready(function() {
alert("Jquery works");
});
The click event will trigger to whatever you're bound do. the only time you'd have to be worried is if you bound to both a parent and child (e.g. you had listed #my_special_id,.switch-small--then you'd have to look at e.target).
With that said, you can use scope to limit how jQuery finds the div:first-child. I'm not 100% sure what you're after, but the below appears to do what you're after:
$(document).ready(function() {
$('#my_special_id').click(function() {
// look for div:first-child within `this` (where `this=#my_special_id`
// per the .click selector above)
if ($('div:first-child',this).hasClass('switch-on')) {
window.alert('ON!');
}
});
});
If you're looking to bind to the on/off separately, you may want to change it around a bit. we can still check for .switch-on, just have to traverse differently:
// here we bind to the on/off buttons and not the container
$('#my_special_id .switch-small').click(function(){
// you want the facsimilee of `div:first-child`, so (because we're now
// within that node, we use .parent() to get back up to it
var $firstChild = $(this).parent();
if ($parent.hasClass('switch-on')){
alert('ON!');
}
});

select the Div without specific content

Q:
I have the following case :
Div contains a link , i wanna to just select the div without the link,i mean ,when clicking on the div i wanna specific action differs from clicking the link.through some JQuery.
the structure i work on is:(by firebug)
<div class ="rsAptContent">
sql
<a class = "rsAptDelete" href = "#" style ="visibility: hidden;">Delete</a>
</div>
the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$(".rsAptContent").click(function(e) {
ShowDialog(true);
e.preventDefault();
});
});
function ShowDialog(modal) {
$("#overlay").show();
$("#dialog").fadeIn(300);
if (modal) {
$("#overlay").unbind("click");
}
else {
$("#overlay").click(function(e) {
HideDialog();
});
}
}
function HideDialog() {
$("#overlay").hide();
$("#dialog").fadeOut(300);
}
</script>`
when i click on the link ,i don't want to execute the Jquery code , how to select the div without the link in.
thanks in advance
Are you looking for something like the stopPropagation() code?
$(".rsAptContent").click(function(e) {
e.stopPropagation();
ShowDialog(true);
return false;
});
});
That should stop the link from executing.
http://api.jquery.com/event.stopPropagation/
Edit: Distinguish between clicking the link and clicking on any part of the content except the link
$(".rsAptContent").click(function(e) {
var $target = $(e.target);
if($target.is(a){
// It's the link.
}else{
// else it's not
}
});
});
Check for the clicked target element than perform action
to get info about which element is click use below script
function whichElement(event){
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
Try this:
$(".rsAptContent").click(function(e) {
if($(e.target).hasClass('rsAptDelete')) return false;
ShowDialog(true);
e.preventDefault();
});
});
If the target is the link the event is cancelled;
If you already have a click handler on the delete link, then just stop the event propagation there by using stopPropagation().
$(".rsAptDelete").click(function(e) {
e.stopPropagation();
});

Categories

Resources