Differentiating "on" click events in jquery - javascript

I have a page which has an event as follows:
$(document).on("click","#div",function(e){
//do the operation
});
This event gets executed on both page load as well as div click.
I need to differentiate between these two calls inside the event, because I have to write a condition extra only on div click and not on load .
How do I know if its from page load or div click?
Edit
On load:
$(default).find('a').trigger("click") ; makes it trigger on load

$(document).on("click", "#div", function(e) {
if (e.originalEvent !== undefined) {//use the originalEvent
alert('human');
} else {
alert('load click')
}
});
$('#div').click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>click</div>

//You can check for originalEvent element present in event object.
$(document).ready(function() {
$(document).on("click","#div",function(e){
if(e.originalEvent) {
alert('clicked manually');
} else {
alert('page load');
}
});
$('#div').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="div">
div
</div>
</body>

You could set a boolean variable in each of these like:
var fromPageLoad = false;
var fromDivClick = false;
$(window).load(function() {
fromPageLoad = true;
//do the operation
});
$(document).on("click","#div",function(e){
fromDivClick = true;
//do the operation
});
and then check which condition is true with an if or a switch statement.
[EDIT]
Unless you want alerts popping out of the blue like the other answers suggest settings variables as so is the way to go.

if u need to perform any action on page load you have to specify as below
$(document).load(function(){
alert("event on page load");
});
if the div click event then as below
$(#div).onclick(function(){
alert ("on div click");
})

Related

JS codes run twice in the page

These codes are in a html page:
$(".link").click(function() {
alert('hey you');
});
$(".link").click(function() {
alert('hey you');
});
and cause twice alert when .link element is click. Why is it so? And how can I prevent it?
Try with off().
$(".link").off().on("click", function() {
alert('hey you');
});
$(".link").off().on("click", function() {
alert('hey you');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='link'>Test</span>
This below code snippet will give you an ideas whats happening and how can you avoid this. As whenever you code executes it registeres a click handler on the element. So you need to make sure that happens only once. Or you need to remove the existing handlers and the register a new one.
.off and .on see for more details
$(document).ready(() => {
$(".link").click(function() {
alert('hey you');
});
$(".link").click(function() {
alert('hey you 1');
});
$(".link2").click(function() {
alert('hey you 1');
});
$(".link3").off().on("click", function() {
alert('hey you 3');
});
$(".link3").off().on("click", function() {
alert('hey you 4');
});
$(".link3").off().on("click", function() {
alert('hey you 5');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="link">Link1</button>
<button class="link2">Link2</button>
<button class="link3">Link3</button>
if you have something like ajax loader, and want to attach event to newly loaded elements, you can mark the already attached elements so that when you next attach it, you don't re-attach the function.
like this:
function attachEvent(){
$('.class-selector:not(.marked)') // only select element that have not been attached
.addClass('marked') // mark it as attached
.on('click', someFunction); // attach the event
}
function someFunction(){
alert('hohoho');
}
function loadAjax(){
$.ajax({url: 'some-url', success: function(){
// add newly loaded element here
// attach event to them
attachEvent();
});
}
of-course you can use detach and re-attach approach, but this might cause problem when you need to have multiple events on the element

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);
});

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();
});

How to stop onclick event in div from propagating to the document?

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.
I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?
<head>
<script>
function showMenu(element) {
alert("div clicked");
event = element.onclick; // HOW TO GET HOLD OF THE EVENT?
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
document.onclick = function() {
alert('document clicked');
};
</script>
</head>
<body>
<div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>
or click outside the div.
</body>
Change your function definition to include the event:
function showMenu(event, element) {
alert("div clicked");
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
Then change the call to pass in the event:
div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
Try EventListeners:
html:
<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​
js:
function showMenu(e) {
alert("div clicked");
}
document.onclick = function() {
alert('document clicked');
};
window.onload = function(){
document.getElementById("fooddmenu").addEventListener("click", function(e){
showMenu(this);
e.stopPropagation();
});
};
Add the onclick to the body element.
Douglas,
It does stop the event from getting bubbled up.
Check this out http://jsbin.com/ahoyi/edit
here, if you comment the alert statement, it will show 2 alerts on clicking the smaller box else only one.
Hope this helps.
well, that's a jquery code.
$("#id") same as document.getElementById("id")
.click function is same as addEvent("click", function() { ... } );
so basically both the functions there are click handlers for Parent and Child DIVs.
Observe the output by commenting / uncommenting the "return false;" statement.
Hope that helps.
By the way, sorry for that "$" confusion.
$("div").click(function(){
...
...
...
return false; //this will stop the further propagation of the event
});
Add Pointer-events: none to the particular element will help to stop pointer events.
event.StopPropagation() will help us to avoid child propagating

jquery: get mouse click if inside a div or not

i have this HTML page
<html>
<body>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
<div id='in_or_out'>e</div>
<div>f</div>
</body>
</html>
a,b,c,d,e and f could be divs also not just a plain text.
I want to get the mouse click event, but how could i know if it's inside or outside #in_or_out div ?
EDIT :: guys, i know how to check if the div is click or not, but i want my event to be fired when the click is outside that div
$("body > div").click(function() {
if ($(this).attr("id") == "in_or_out") {
// inside
} else {
// not inside
}
});
EDIT: just learned, that there is a negate:
$("body > div:not(#in_or_out)").click(function(e) {
// not inside
});
If you want to detect whether or not you've clicked inside or outside the div, set the event handler on the documentElement and let it propagate from the other elements upwards:
$("html").click(function (e)
{
if (e.target == document.getElementById("in_or_out"))
alert("In");
else
alert("Out!");
});
Maybe this one will help you
$('body').click(function(){
//do smth
});
$('div#in_or_out').click(function(e){
e.stopPropagation();
// do smth else
});
Depends what you want. If you only want to execute code, when it was inside #in_or_out, you can do:
$('#in_or_out').click(function(){ /* your code here */ });
You can have a status variable that says whether the mouse is in #in_or_out or not:
var inside = false;
$('#in_or_out').hover(function() { inside = true; }, function() { inside = false; });
Then whenever a click occurs you can check with inside whether the click was inside in_or_out or not.
Reference: .hover()
Update:
No matter to which element you bind the click handler, you can always do this:
$('element').click(function() {
if ($(this).attr('id') !== 'in_or_not') {
}
});
for inside it would be
$("#in_or_out").click(function() {
// do something here
});
for outside...I've got no idea.
Edit: You could try to do the same for body-tag (assigning a click-handler to the document itself). But I'm not sure if both events would fire by that.
Like this?
$("#in_or_out").click(function() {
alert("IN DIV!");
});

Categories

Resources