I'm using dropdown functionality of bootstrap and I have this dropdown in container, but in outside I have wrapper, which is reacting on the same event (onclick), so I do
e.stopPropagation();
because I don't want to react on event in wrapper, when I'm clicking dropdown button. Unfortunately, this code also stops my dropdown event. Is it possible to avoid this behaviour and display only dropdown list, without alert?
https://jsfiddle.net/hms5265s/
Here is my solution.
document.querySelector('.container').addEventListener('click', (e) => {
if($(e.target).is("#dropdown")){
alert('work');
}
else{
e.stopPropagation();}
});
If you want your alert to be called on the click event of the wrapper but not the click event of the dropdown iteself you can try something like this
document.querySelector('#wrapper').addEventListener('click', (e) => {
var source = event.target || event.srcElement;
console.log(source.id);
if (source.id !== 'someId') {
// do some stuff
alert("I don't want this alert");
}
// you can stop the even propagation here if you want to.
});
Here is a JSFiddle
If you also don't want to assign an Id for your dropdown you can also check for a class.
here is my solution
Element.prototype.hasClass = function(className){
tClassName = this.className;
return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};
document.querySelector('#wrapper').addEventListener('click', (e) => {
console.log('clicked' + e.target.hasClass('dropdown-toggle'));
if(e.target.hasClass('dropdown-toggle')) return
alert("I don't want this alert");
});
document.querySelector('.dropdown-menu').addEventListener('click', (e) => {
e.stopPropagation();
});
https://jsfiddle.net/hms5265s/6/
updated solution:
Element.prototype.hasClass = function(className){
tClassName = this.className;
return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};
document.querySelector('#wrapper').addEventListener('click', (e) => {
if(e.target.hasClass('dropdown-toggle')) return
alert("I don't want this alert");
});
document.querySelector('.container').addEventListener('click', (e) => {
if(! e.target.hasClass('dropdown-toggle')){
e.stopPropagation();
}
});
https://jsfiddle.net/hms5265s/12/
Related
I have function which has keyup event on input field which is working fine.
I want to trigger this function also upon click on other button.
Here is my function
function validateChild(el) {
var validated = {};
console.log('Remove button clicked');
var dateOfBirthField = $(el).find('.date_of_birth');
$(dateOfBirthField).on("keyup", function () {
var dateOfBirthValue = $(el).find('.date_of_birth').val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
});
}
I'm calling this function on document load
function validateForms() {
$(document).find(".child-form").each(function () {
validateChild(this);
});
}
Here i have click event
.on('click', '.removeButton', function (event) {
validateForms();
});
When i click on this remove button it trigger but stop working after this
console.log('Remove button clicked');
How can i trigger keyup event also on this remove button, or there is better way to do this in javascript.
Can anyone help me with this?
Thanks
I have reviewed your three code blocks. Please try following three code blocks respectively.
Your function
function validateChild(dateOfBirthField) {
var validated = {};
var dateOfBirthValue = $(dateOfBirthField).val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
}
Call this function on document load
function validateForms() {
$('.child-form').on('keyup', '.date_of_birth', function() {
validateChild(this);
});
}
Click event
.on('click', '.removeButton', function() {
console.log('Remove button clicked');
$('.child-form .date_of_birth').each(function() {
validateChild(this);
});
});
I have circle menu with rotation. And after simple click i want to fire click event, but during rotation - mousemove i want ignore click. For now i have -
<g id="bottomMenuRotate" onMouseDown={this.selectElement.bind(this)}>
Then my select function looks -
selectElement(e){
let groupRotate = document.getElementById('bottomMenuRotate');
groupRotate.onmousemove = function(e) {....}
groupRotate.onmouseup = function(e){
groupRotate.onmousemove = null;
}
}
So how i cant prevent click? I tried something like
groupRotate.onmouseup = function(e){
e.stopPropagation();
groupRotate.onmousemove = null;
};
or
groupRotate.onmouseclick = function(e){
e.stopPropagation();
}
but this prevents every click. Any tips how i can do it?
So i finally found simply solution
selectElement(e){
let move = false;
groupRotate.onmousemove = function(e) {
move = true;
}
groupRotate.onclick = function(e){
move ? e.preventDefault() : false;
}
}
This prevent click only when move is set to true.
Set a state in your onMouseMove handler that prevents the click events from running:
groupRotate.onmousemove = (e) => {
this.setState({ mouseMoving: true });
}
groupRotate.onmouseup = (e) => {
this.setState({ mouseMoving: false });
}
Somewhere else:
groupRotate.onmouseclick = (e) => {
if (!this.state.mouseMoving) {
...
};
}
Note the arrow functions to make this available within the functions.
I have a <ul> element that opens a bootbox when it's clicked. Double clicking this element triggers the onclick in JQuery twice
$("#email-list").on("click", ".list-group-item", function (e) {
bootbox.confirm("Send a forgotten password email to " + email + "?", function (result) {...}}
I tried using 'e.preventDefault()'
$(document).ready(function () {
$("#email-list").dblclick(function (e) {
e.preventDefault();
});
});
I even tried disabling clicking on the element but both failed. The bootbox still appears twice.
$("#email-list").bind('click', function () { return false; });
//...do stuff
$("#email-list").unbind('click');
Anyone has a suggestion?
Another solution can be to add:
bootbox.hideAll();
to hide any other bootboxes right before showing the bootbox like so:
bootbox.hideAll();
bootbox.confirm("Some Message " , function (result){/*do stuff*/}
Try this:
$("#email-list").on("click", ".list-group-item", function (e) {
if(!$('#myModal').is(':visible')){
$('#myModal').modal('show');
}
e.preventDefault();
}
Use the click event, then you can replace
e.preventDefault();
with
e.stopPropagation();
or
return false;
I figured the best way to do this is to separate the two events; onclick and dbclick, I used something like this, I hope it will save someone some time:
var DELAY = 700, clicks = 0, timer = null;
$(function () {
$("#email-list").on("click", ".list-group-item", function (e) {
clicks++; //count clicks
if (clicks == 1) {
//do stuff
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
clicks = 0; //after action performed, reset counter
return false;
}
})
.on("dblclick", function (e) {
e.preventDefault(); //cancel system double-click event
});
}
I need to temporarily change the click event for an element as follows:
var originalEvent = '';
$("#helpMode").click(function (e) {
originalEvent = $("#element").getCurrentClickEventHandler();
$("#element").click(function (e) {
//Do something else
});
});
//Later in the code
$("#helpModeOff").click(function (e) {
$("#element").click(originalEvent);
});
How would I store the current function that is an event handler in a global variable for later reuse?
EDIT: Here's what im trying to do:
var evnt = '';
$("#helpTool").click(function (e) {
if(!this.isOn){
evnt = $("#Browse").data('events').click;
$("#ele").unbind('click');
$("#ele").click(function (e) {
alert('dd');
});
this.isOn=true;
}else{
this.isOn = false;
alert('off');
$("#ele").unblind('click');
$("#ele").click(evnt);
}
});
Here you go, figured it out:
Now with e.srcElement.id you can get either HelpMode or HelpModeOff and then can turn on/off your help stuff!
http://jsfiddle.net/zcDQ9/1/
var originalEvent = '';
$('#element').on('yourCustomEvent', function (e) {
// do stuff
alert(originalEvent);
$(this).toggleClass('toggleThing');
//test for helpMode or helpModeOff here now...
});
$("#helpMode").on('click', function (e) {
originalEvent = e.srcElement.id;
$("#element").trigger('yourCustomEvent');
});
//Later in the code
$("#helpModeOff").on('click', function (e) {
originalEvent = e.srcElement.id;
$("#element").trigger('yourCustomEvent');
});
Okay. In jQuery 1.7 I guess it's a little different.
//get the handler from data('events')
$.each($("#element").data("events"), function(i, event) {
if (i === "click") {
$.each(event, function(j, h) {
alert(h.handler);
});
}
});
http://jsfiddle.net/yQwZU/
This is the reference.
Not sure if the following works with 1.7.
originalEvent = $('#element').data('events').click;
jQuery stored all the handlers in data. See here to learn more about data('events').
Personally, I think I would avoid manually binding and unbinding handlers.
Another way to approach this is to bind click events to classes, then all you need to do is add and remove classes from the appropriate elements when switching to/from help mode.
Here's a jsfiddle illustrating what I mean.
Switching to and from help mode then just involves adding removing classes:
$('#btnhelpmode').click(function(){
if(!helpMode){
helpMode = true;
$('.normalmode').addClass('helpmode').removeClass('normalmode');
$(this).val('Switch to normal mode...');
}else{
helpMode = false;
$('.helpmode').addClass('normalmode').removeClass('helpmode');
$(this).val('Switch to help mode...');
}
});
and you just create the handlers required, binding them to the appropriate classes:
$('#pagecontent').on('click', '#element1.normalmode', function(){
alert('element1 normal mode');
});
$('#pagecontent').on('click', '#element1.helpmode', function(){
alert('element1 help mode');
});
$('#pagecontent').on('click', '#element2.normalmode', function(){
alert('element2 normal mode');
});
$('#pagecontent').on('click', '#element2.helpmode', function(){
alert('element2 help mode');
});
$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});