html div onclick event - javascript

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

Related

Capturing an event with jquery

I got a double event to manage. The two events are both "click" and they're handled with jquery. The html is the following:
<div class="siteMap" style="width:23%;">
<h5>Divisione Anticontraffazione</h5>
<span class="menufooter">
<span class="link1">Introduzione</span><br>
<span class="link2">Filosofia</span><br>
<span class="link3">Negozio online</span></span><br>
</div>
Then i have my click events which fires inside the menufooter span and inside every single link span. The code is like this:
$(document).ready(function() {
$('span.menufooter').click(function() {
//my code here
});
$("span.link1").click(function() {
//my code here
});
});
I need an event capturing action, the click on the span menufooter has to fire the event before the click on the span link1 fires. At this point, none of the two events is firing. Any hint?
How about only fire event on .menufooter
$(document).ready(function() {
$('span.menufooter').click(function(e) {
//my code here 1
// Capture Event Propagation
if ( $("span .link1").find(e.target).length>0 ){
//my code here 2
};
});
});
http://jsfiddle.net/9QLtG/
You could prevent the click from bubbling, and then trigger the click on the parent element so whatever is in that handler executes first (unless it's async)
$(document).ready(function () {
$('.menufooter').click(function () {
// fires before ....
});
$("span.link1").click(function (e) {
e.stopPropagation();
$('.menufooter').trigger('click');
// .... this fires, as it's triggered above
});
});
FIDDLE
I would have 1 click listener that listens to the wrapper. You can check the event's target to see if they actually clicked on a link and run code accordingly.
For example:
$(document).ready(function() {
$('.container').click(function(e) {
// Perform action when they clicked in the main wrapper,
// regardless of whether or not it was a link.
console.log("I clicked in the wrapper...");
if ($(e.target).hasClass('link')) {
// Perform action if they clicked on a link.
console.log("...but more specifically, on a link.");
}
});
});
Here's a fiddle that demonstrates this: http://jsfiddle.net/WaYFr/
Try this event.stopPropagation();
$("span.link1").click(function(event) {
event.stopPropagation();
...
});

jquery click event on element not having a class

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.
DO NOT PROCESS:
<a class="iconGear download disablelink" href="#">Download</a>
PROCESS:
<a class="iconGear download" href="#">Download</a>
tried this without success:
$("a.download").not(".disablelink").click(function (e) {
alert('in');
e.preventDefault();
});
This should work:
$("a.download:not('.disablelink')").click(function (e) {
alert('in');
e.preventDefault();
});
If the disablelink class is being added dynamically:
$(document).on('click', "a.download:not('.disablelink')", function (e) {
alert('in');
e.preventDefault();
});
Check this demo: http://jsfiddle.net/d3rXr/1/
$('a.download').click(function(e){
e.preventDefault();
if($(this).hasClass('disablelink')){
return;
}else{
//other stuff;
}
});
Why don't you check when the anchor is clicked, and if it has the class it returns and does nothing, which would be more readable code I guess.
You could go like this:
$("a.download").click(function(e) {
if($(this).hasClass("disablelink")) {
return false;
}
// Normal code
alert('in');
e.preventDefault();
});
Firstly, this probably doesn't work because some links had disablelink added to them dynamically, and after they already had the click handler bound to them.
Secondly, you should just check for that class inside the click handler, like so:
$("a.download").click(function (e) {
if($(this).hasClass('disablelink')){
e.preventDefault();
// link is disabled
}else{
alert('in');
// link is active
}
});

jQuery, Triggering event from Class

Please take a look at the following code and fiddle.
CODE
$("#enable").click(function(e) {
if (!$("#enable").data('isOn')) {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '1px solid red');
$(this).addClass('clickEnabled');
});
$("#enable").data('isOn', true);
} else {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '');
$(this).removeClass('clickEnabled');
});
$("#enable").data('isOn', false);
}
});
$(".clickEnabled").click(function(e) {
alert('clicked');
});
Fiddle: http://jsfiddle.net/qAuwt/
I am basically trying to toggle a "clickEnabled" class on elements when a button is pressed. The toggling is working as the border is changing however the clickEnabled class is not responding to click events
There are no .clickEnabled elements when you set the event handler. You can still catch the click event, though:
$(document).on("click", ".clickEnabled", function(){
alert("Hello, world!");
});​
Change:
$(".clickEnabled").click(function (e) {
alert('clicked');
});
To:
$(".clickable").click(function (e) {
if ( $(this).hasClass("clickEnabled") )
{
alert('clicked');
}
});
As #araxanas mentioned, the .clickEnabled don't exist on load. So I switched the selector to .clickable, which do. However, you only want to handle the click when they're enabled. That's why I've added the conditional. It'll only alert if the clicked element has the clickEnabled class.
Also, it might help to move the css out of javascript, that way you can see visually if the class is there or not, see my updated fiddle.
The problem is that when page loaded, the click event handler binds to no elements (because there is no element with class 'clickEnabled').
The solution is to change the .click() method to .live() method:
$(".clickEnabled").live('click', function (e) {
alert('clicked');
});

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