Custom Context Menu on everything except "input" in jQuery - javascript

I want to add custom context menu with jQuery for the whole body of the page, except the textfields. How can I do that?
I have tried that code:
$('body:not(input)').bind('contextmenu', function(){
/*code*/
});

Check the srcElement before plugin executions. If it's not an input element, do trigger the contextmenu plugin:
$(document).on("contextmenu", function(e) {
if (!$(e.srcElement).is(":input")) { // if it's not an input element...
$(this).triggerTheContextMenuPlugin();
}
});

Use an event listener on the document and check if it was initiated by an input element.
$(document).on("contextmenu", function (e) {
if (e.target.tagName.toUpperCase() === "INPUT") {
console.log("context menu triggered");
}
});
Demo here

Inspired by Salman's solution.
You can stop the event propagation in all input elements, with the e.stopPropagation() function. In doing so, you keep the default behavior of the inputs elements:
$(function() {
$(document).on("contextmenu", function(e) {
alert("Context menu triggered, preventing default");
e.preventDefault();
});
$("input").on("contextmenu", function(e) {
e.stopPropagation();
});
});
JSFiddle Demo

Related

Prevent event from triggering

I got two functions, one that collapses stuff when someone clicks the header of that collapsable, and I got a function that opens a modal, but the open modal icon that I use as a trigger to open the modal, is on the header of the collapsable, so when someone clicks the icon, it both opens the modal, and does the collapse stuff, but I just want to open the modal and not do the collapse stuff, so how can I prevent it from triggering my collapse?
Collapse
$(document).on('click', '.panel-heading', function () {
var valgtElement = $(this).next();
$.each($('.panel-collapse'), function (index, value) {
if ($(this).attr('id') == valgtElement.attr('id')) {
$(this).collapse('toggle');
} else {
if ($(this).hasClass('in')) {
$(this).collapse('toggle');
}
}
});
});
Icon click
$('body').on('click', '.fa-trash-o', function () {
$('#slettModal').modal();
});
Use stopPropagation
$('body').on('click', '.fa-trash-o', function (e) {
e.preventDefault();
e.stopPropagation();
$('#slettModal').modal();
});
just use event.stopPropagation()
Link for more details
$('body').on('click', '.fa-trash-o', function (e) {
e.preventDefault();
e.stopPropagation();
$('#slettModal').modal();
});
Try this
$('body').on('click', '.fa-trash-o',
function (event) {
event.stopImmediatePropagation()
$('#slettModal').modal();
});
make sure to include the event parameter in the function declaration
http://api.jquery.com/event.stopImmediatePropagation/
How to prevent other event handlers, from first handler, in jQuery

Using :not() to ignore clicks on children links?

In a script I'm writing with JQuery I'm trying to add a click handler to a div, but ignoring clicks on the children a tags inside it.
You can see a JSFiddle of how I'm currently trying (and failing) to make it happen here: http://jsfiddle.net/q15s25Lx/1/
$(document).ready(function() {
$(document).on('click', '.post:not(a)', function(e) {
alert($(this).text());
});
});
<div class="post">This is some text in a div. Click me please.</div>
In my real page, the a tags all have their own click handlers, so I need to be able to listen for those concurrently.
So, ideally I'd like to use something like the :not() selector to ignore clicks on this particular handler.
Is something like this possible?
You'll need to add another handler that acts on the anchor and stops the event from propagating:
$(document).on('click', '.post a', function (e) {
e.stopPropagation();
e.preventDefault();
});
Without this, when you click the a the event bubbles up to the parent .post, and the handler fires on that anyway.
You need to stop event propagation to child elements using .stopPropagation():
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
});
Working Demo
Just return false; in the end of event handler.
$(document).on('click', '.post', function (e) {
alert($(this).text());//will show entire text
});
$(document).on('click', '.post a', function (e) {
alert($(this).text());//will show 'text'
return false;
});
working fiddle: http://jsfiddle.net/q15s25Lx/2/
return false will server as both e.preventDefault() &
e.stopPropagation()
Try to stop the event from bubbling up the DOM tree using stopPropogation()
$(document).ready(function() {
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
alert($(this).text());
});
});
Fiddle Demo
All of the other posts did not explain why your code failed. Your selector is saying : Find an element that has the class post and is not an anchor. It is NOT saying if a child was clicked and was an achor do not process.
Now there are two ways to solve it. One is to prevent the click from bubbling up from the anchors. You would add another listener on the anchors.
$(document).on('click', '.post a', function (evt) {
evt.stopPropagation(); //event will not travel up to the parent
});
$(document).on('click', '.post', function (evt) {
console.log("Click click");
});
Or the other option is not to add a second event, but check what was clicked.
$(document).on('click', '.post', function (evt) {
var target = $(evt.target); //get what was clicked on
if (target.is("a")) { //check to see if it is an anchor
return; // I am an anchor so I am exiting early
}
console.log("Click click");
});
Or jsut let jquery handle it all for you. return false
$(document).on('click', '.post:not(a)', function() {
alert($(this).text());
return false;
});

Prevent Bootstrap dropdown from closing on clicks [duplicate]

This question already has answers here:
How do I prevent my dropdown from closing when clicking inside it?
(3 answers)
Closed 4 years ago.
My menu uses Bootstrap 3 and I can't prevent dropdown from closing on click. How can I do it?
JSFiddle
// Add open class if active
$('.sidebar-nav').find('li.dropdown.active').addClass('open');
// Open submenu if active
$('.sidebar-nav').find('li.dropdown.open ul').css("display","block");
// Change active menu
$(".sidebar-nav > li").click(function(){
$(".sidebar-nav > li").removeClass("active");
$(this).addClass("active");
});
// Add open animation
$('.dropdown').on('show.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// Add close animation
$('.dropdown').on('hide.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
You need to stop event from bubbling up the DOM tree:
$('.dropdown-menu').click(function(e) {
e.stopPropagation();
});
event.stopPropagation prevents event from reaching the node where it's eventually handled by Bootstrap hiding menu.
Demo: http://jsfiddle.net/wkc5md23/3/
I believe this should be a more proper solution, as stopping propagation on the click event might sometimes cause issues later on in development. You may read more into it here: http://css-tricks.com/dangers-stopping-event-propagation/ Instead this solution stops propagation on the Bootstrap hide (hide.bs.dropdown) event, which stops it from continuing on to the hidden (hidden.bs.dropdown) event.
The following code has been taken and edited by myself to make it work on all Bootstrap dropdowns, as it has originally been taken from here: Preventing bootstrap dropdown from closing on click I personally prefer this way also because it uses the built in Bootstrap dropdown events, which could be found here: https://getbootstrap.com/docs/3.4/javascript/#dropdowns-events.
$(function () {
$('.dropdown').on({
'click': function (event) {
if ($(event.target).closest('.dropdown-toggle').length) {
$(this).data('closable', true);
} else {
$(this).data('closable', false);
}
},
'hide.bs.dropdown': function (event) {
hide = $(this).data('closable');
$(this).data('closable', true);
return hide;
}
});
});
You can disable the dropdown functionality temporarily. This is a workaround.
Example with input field inside the drop-down "menu":
//for dropdown field not closing when clicking on inputfield
$(document).on('focus', 'input', function (e) {
// this attribute can be anything except "dropdown", you can leave it blank
$('#yourDropdownID').attr('data-toggle', 'off');
});
//for dropdown field back to normal when not on inputfield
$(document).on('focusout', 'input', function (e) {
$('#yourDropdownID').attr('data-toggle', 'dropdown');
});
This can be used on anything that is clickable and you can define individually what items clicked can close or not close the drop-down menu.
Not close in click out side menu
$(function() {
var closeble = false;
$('body').on('click', function (e) {
if (!$(event.target).is('a.dropdown-toggle')) {
closeble = false;
}
});
$('.dropdown').on({
'click': function (event) {
if ($(event.target).closest('.dropdown-toggle').length) {
closeble = true;
} else {
closeble = false;
}
},
'hide.bs.dropdown': function () {
return closeble;
}
});
});

how to target event for "shift keydown & click" on a div?

I want to control events when hovering a <div> element.
I have my code pretty much working, but I have 2 remaining problems!
When I first run the code in my JSFiddle, I need to click on the body of the document first to get the keydown to be recognised. If I run the code and hover right away and press shift nothing happens. I have it running on doc ready,so not sure why I need to click first? Anyway to get this to work right way without needing to click?
I trace out in the console the console.log('click and press'); This is getting fired each time I press shift and is not looking for a click - why is this getting fired when pressing shift when I call it within a function that says $(document).on('keydown click', function (e) {
DEMO
My JS code is as follows
$(document).ready(function () {
$(".target").hover(function () {
$(document).on('keydown click', function (e) {
if (e.shiftKey) {
// code to go here for click
console.log('click and press');
}
});
$(document).on('keydown', function (e) {
if (e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
$('.target').css('cursor', 'sw-resize', 'important');
});
});
});
Thanks
Your event binding is incorrect. you can use:
Demo: http://jsfiddle.net/g9ea8/8/
Code:
$(document).ready(function () {
var hovering = false;
$(".target").hover(function () {
hovering = true;
}, function() {
hovering = false;
});
$(document).on('click', function (e) {
if (hovering && e.shiftKey) {
// code to go here for click
console.log('hovering+shift+click');
}
});
$(document).on('keydown', function (e) {
if (hovering && e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
console.log('hovering+shift');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
if(hovering) {
$('.target').css('cursor', 'sw-resize', 'important');
console.log('hovering+keyup');
}
});
});
The reason why you need to click first on the fiddle demo is because the frame doesn't have focus, normally this should work fine.
You shouldn't be attaching a keydown listener, you only need a to attach click, otherwise keydown will fire the event regardless of a click occurring.
Also, currently you're attaching 3 handlers every time you hover over .target, see #techfoobar's answer for a cleaner solution.

jQuery event contextmenu triggers underlaying div

looking at this event (being bind on 2 divs overlapping each other, look at the jsfiddle)
.on('contextmenu', function() { ... });
Why do both divs being triggered?
How can I detect this and or stop the underlaying div from triggering?
DEMO: jsfiddle
Thanks for any information!
On nested element, you need to stop event bubbling:
$('#div2').on('contextmenu', function(e) {
e.stopPropagation();
$('#log').append('<p>div2 triggered contextmenu!</p>');
});
DEMO
DEMO
$('#div1,#div2').on('contextmenu', function (e) {
e.stopPropagation();
$('#log').append('<p>' + e.target.id + ' triggered contextmenu!</p>');
});
event.target
event.stopPropagation/
You need to prevent event from propogating, try this code:
$('#div1').on('contextmenu', function(e) {
if(!e.isDefaultPrevented()){
$('#log').append('<p>div1 triggered contextmenu!</p>');
e.preventDefault();
}
});
$('#div2').on('contextmenu', function(e) {
if(!e.isDefaultPrevented()){
$('#log').append('<p>div2 triggered contextmenu!</p>');
e.preventDefault();
}
});

Categories

Resources