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');
});
Related
I looked at http://api.jquery.com/trigger/ and the examples did not answer my question. I am looking at some code and would like to know what this block of code is doing.
$(document).on('click', '#SubmitQuery', function(event) {
event.preventDefault();
$(document).trigger('filter:submit');
});
Specifically, what does the colon inside of that trigger function do? For complete context, here is what filter is (I assume that the 'filter' inside of the trigger function refers to that filter object):
var filter = {
init: function() {
$(document).on('keypress', '#Filter', debounce(function(event) {
if (event.keyCode == 13) {
$(document).trigger('filter:text');
}
}, 300));
$(document).on('click', '#ClearFilter', function(event) {
event.preventDefault();
$('#FilterText').val('');
$('#FilterText').focus();
$(document).trigger('filter:clear');
});
$(document).on('change', '.filterSection [type=checkbox]', function(event) {
var group = $(this).parents('[data-filter-group]').attr('data-filter-group');
var $checkboxes = $('[data-filter-group=' + group + '] [type=checkbox]');
if ($checkboxes.length > 0) {
if ($checkboxes.filter(':checked').length === 0) {
$(this).prop('checked', true);
}
}
});
$(document).on('click', '#SubmitQuery', function(event) {
event.preventDefault();
$(document).trigger('filter:submit');
});
$("#Filter").focus();
}
};
The colons specifies custom events, essentially creating namespaces for events you can call later without overriding default events or having to create multiple listeners on the same event.
You can find more information here: https://learn.jquery.com/events/introduction-to-custom-events/
I have some question with these events.
My code is something like this:
dialogX.find('#inputExample').blur(function() {
var button = $(this).parent().find('#buttonExample');
if(!(button.is(':clicked'))) //this doesn't work, just test
button.hide();
});
dialogX.find('#buttonExample').live('click', function() {
alert('Test!');
$(this).hide();
});
The question is, when I'm on input (#inputExample) and later click on button (#buttonExample), blur is called and live event is never called.
***I have to use live instead of on, because JQuery version.
Someone could help me?
dialogX.find('#inputExample').blur(function() {
var button = $(this).parent().find('#buttonExample');
if(disableBlur)
button.hide();
});
var disableBlur = false;
dialogX.live('mousedown', function(e) {
if($(e.target).prop('id')=='buttonExample')
disableBlur = true;
else
disableBlur = false;
});
Can someone explain me why this snippet can't work ?
I can't use specific features like window.location, submit(), (instead of trigger()), because this function is bound to elements that are very differents.
$('a, button').bind('click', function(oEvent, oData) {
var oButton = $(this);
var bSkip = (oData && oData.skip);
if(true === bSkip) {
return true;
} else {
oEvent.preventDefault();
//oEvent.stopPropagation();
if(confirm('This is a confirm box')) {
$(oButton).trigger('click', { skip: true });
}
}
});
Thanks in advance ! ;)
In your case even though the click event gets fired the default behavior of the links may not be triggered because of the constraints imposed by the browser
If I understand what you are trying to do correctly(if the action s not confirmed then cancel the default behavior), then you can achieve it by the below... there is no need to fire the event again
$('a, button').bind('click', function (oEvent, oData) {
if (confirm('This is a confirm box')) {
return true;
} else {
oEvent.preventDefault();
}
});
Demo: Fiddle
This question already has answers here:
How can I check if a key is pressed during the click event with jQuery?
(5 answers)
Closed 5 years ago.
I need to know if the user is clicking or CONTROL CLICKING a div element.
I have seen examples on how to do it using event listeners.. but my code is already set in place, and is using an on-element onclick method..
HTML
<div id='1' onclick='selectMe()'>blah</div>
JS
function selectMe(){
//determine if this is a single click, or a cntrol click
}
...also would love to know if it was a left or right mouse button click.
In your handler, check the window.event object for the property ctrlKey as such:
function selectMe(){
if (window.event.ctrlKey) {
//ctrl was held down during the click
}
}
UPDATE:
the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:
HTML
<span onclick="handler(event)">Click me</span>
JS
function handler(ev) {
console.log('CTRL pressed during click:', ev.ctrlKey);
}
The same applies for keyboard events
See also
KeyboardEvent.getModifierState()
2021 UPDATE: There are better ways to do this now. Please be sure to check out the other answers
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey.
Look down for example
$("xyz").click(function(e)){
if(e.ctrlKey){
//if ctrl key is pressed
}
else{
// if ctrl key is not pressed
}
}
note: https://www.w3schools.com/jsref/event_key_keycode.asp
Try this code,
$('#1').on('mousedown',function(e) {
if (e.button==0 && e.ctrlKey) {
alert('is Left Click');
} else if (e.button==2 && e.ctrlKey){
alert('is Right Click');
}
});
Sorry I added e.ctrlKey.
Try this:
var control = false;
$(document).on('keyup keydown', function(e) {
control = e.ctrlKey;
});
$('div#1').on('click', function() {
if (control) {
// control-click
} else {
// single-click
}
});
And the right-click triggers a contextmenu event, so:
$('div#1').on('contextmenu', function() {
// right-click handler
})
You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.
From above only , just edited so it works right away
<script>
var control = false;
$(document).on('keyup keydown', function (e) {
control = e.ctrlKey;
});
$(function () {
$('#1x').on('click', function () {
if (control) {
// control-click
alert("Control+Click");
} else {
// single-click
alert("Single Click");
}
});
});
</script>
<p id="1x">Click me</p>
pure javascript:
var ctrlKeyCode = 17;
var cntrlIsPressed = false;
document.addEventListener('keydown', function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
document.addEventListener('keyup', function(){
if(event.which=="17")
cntrlIsPressed = true;
});
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Can somebody tell me what I am doing wrong?
window.onload = initForm;
function initForm() {
var allTags = document.getElementsByTagName("*");
for(i=0; i<allTags.length; i++) {
if (allTags[i].className.indexOf("textbox") > -1) {
allTags[i].onFocus = fieldSelect;
allTags[i].onBlur = fieldDeSelect;
}
}
}
function fieldSelect() {
this.style.backgroundImage = "url('inputBackSelected.png')";
}
function fieldDeSelect() {
this.style.backgroundImage = "url('inputBack.png')";
}
I am a beginner at JavaScript so I am not used to debugging code yet.
Thanks
Luke
Your problem lies in attaching your event handlers. You should bind to onfocus and onblur (note the lowercase event name).
As a suggestion, you may want to look at a very simple cross browser addEvent() with a quick line of code added to ensure the proper this pointer:
function addEvent(obj, evType, fn, useCapture){
if (obj.addEventListener){
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent){
// fix added by me to handle the `this` issue
var r = obj.attachEvent("on"+evType, function(){
retrun fn.apply(obj, arguments);
});
return r;
} else {
alert("Handler could not be attached");
}
}
And then use the addEvent function instead of allTags[i].onfocus = you will probably have better mileage in the future binding events.
addEvent(allTags[i], 'focus', fieldSelect);
addEvent(allTags[i], 'blur', fieldDeSelect);
jsfiddle demonstration
The problem is that when fieldSelect and fieldDeselect are getting called, this refers to the window object, not to the element that fired the event. You might want to consider using jQuery:
$(document).ready(function() {
$('.textbox').focus(fieldSelect).blur(fieldDeselect);
});
function fieldSelect() {
$(this).css('background-image', 'url("inputBackSelected.png")');
}
function fieldDeselect() {
$(this).css('background-image', 'url("inputBack.png")');
}
jQuery takes care of making sure that when your event handlers are getting called, this refers to the element that fired the event.
Two things, the events should be all lower case (onfocus, onblur) and this doesn't point to the object that triggered the event in IE. Try this:
function fieldSelect(e) {
var event;
if(!e) {
event = window.event;
} else {
event = e;
}
event.target.style.backgroundImage = "url('inputBackSelected.png')";
}
function fieldDeSelect(e) {
var event;
if(!e) {
event = window.event;
} else {
event = e;
}
event.target.style.backgroundImage = "url('inputBack.png')";
}
Standards complient browsers will pass an event object to the event handler. IE uses a global window.event object instead. Either way you can use that object to get the target of the event that triggered the handler.
Another, probably preferable option would be to have your functions set and remove a className instead of directly changing the style. Then put a style called maybe selected in your stylesheet that overrides the background image. That way you keep style info and behavior separate.
Instead of window.onload=initform try window.onload=function(){/the init function/}
Also when refering to a function you should use () even if there are no arguments.