Capturing an event with jquery - javascript

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

Related

How to modify clickable elements in jQuery?

Why doesn't the on click listener work after clicking on the first list-button?
JSFiddle link
$(".acceptTask").on("click", function(){
acceptTask(this);
});
$(".solveTask").on("click", function() {
solveTask(this);
});
function solveTask(e){
...
}
function acceptTask(e){
...
$(document).on("click", ".solveTask", solveTask);
}
$('.solveTask').on('click', /*...*/) only applies the event handler to anything that has a class "solveTask" at that time. So when you add the solveTask class in your acceptTask function, add an event listener.
$(e).addClass('btn-warning solveTask')
.click(function () { solveTask(this); });
See fiddle: https://jsfiddle.net/1203y34b/1/
I had this problem previously and used 'delegate' instead of 'on':
$(document).delegate('.solveTask', 'click', solveTask)

Turn on() event back after apply off

How can I turn an on('click') event back on after I apply event off()?
$('#btn-aluno').on('click', function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').off();
});
$('#btn-familiar').on('click', function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').off();
});
new-step-email-familiar and new-step-email-aluno = <input>
btn-aluno and btn-familiar = <span> (used as a button)
Instead of turning off the event listener, you could do the same thing by using event delegation,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').removeClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').removeClass("active");
});
And whenever you want to activate the event listeners, just add the class active to the relevant elements. Also in the place of document try to use any closest static parent of the element on which the event gonna be bound.
As per your requirement, you have edit your logic like below,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').toggleClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').toggleClass("active");
});
DEMO

class getting added to div on click of parent element

I am trying to do a simple hide & show of a DOM on click event.I am showing the
loadMenu container on clicking of span#dwnTrigger.
But my problem is even when I am clicking on the div#loadMenu , this div#loadMenu is getting hidden. I am not sure how can this happen as the event is attached to span#dwnTrigger.
<span id="dwnTrigger" class="dwnPrint" aria-label="Download" ng-controller="dwnCtrl" > Start
<div class="dwnCtrl menuContainer ng-hide" id="loadMenu">
//rest of DOM
</div>
</span>
Controller
abc.controller('dwnCtrl',['$scope',function($scope){
$scope.$element = $("#dwnTrigger");
($scope.$element).on('click',function() {
if ($("#loadMenu").hasClass('ng-hide')) {
$("#loadMenu").removeClass('ng-hide').addClass('ng-show');
//rest of code
}
else if ($("#loadMenu").hasClass('ng-show')) {
$("#loadMenu").removeClass('ng-show').addClass('ng-hide')
}
})
}]);
This is called event propagation/bubbling. When you click on an element the event propagates through all it's parents. So as the div#loadMenu is a child of span#dwnTrigger the click on div#loadMenu propagates to span#dwnTrigger and triggers it's event handler.
You can use 'event.stopPropagation()' to prevent this. You have to bind an click event handler to div#loadMenu, capture the event and stop propagation.
$('div#loadMenu').click(function(event) {
event.stopPropagation();
});
For more on event.stopPropagation() https://api.jquery.com/event.stoppropagation/ and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
Alternatively you can check which element dispatched the event by event.target and act based on that. For example your click handler can be like following
($scope.$element).on('click',function(event) {
if($(event.target).closest('#loadMenu').length > 0) {
return;
}
if ($("#loadMenu").hasClass('ng-hide')) {
$("#loadMenu").removeClass('ng-hide').addClass('ng-show');
//rest of code
}
else if ($("#loadMenu").hasClass('ng-show')) {
$("#loadMenu").removeClass('ng-show').addClass('ng-hide')
}
})
For more on event.target https://developer.mozilla.org/en-US/docs/Web/API/Event/target

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

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

Categories

Resources