simulated call onMouseDown in console - javascript

There is a div element on the page, by clicking on it a menu with a choice of the displayed number of elements is created.
Menu:
How to call this action through the console (onMouseDown React)?
Code:

In the console you want to grab your element and then use a dispatch event to simulate a mouseover or click
var div = document.querySelector("#myDiv");
var myEventToDispatch = new MouseEvent("click"); //or "mousedown", whichever you need
div.dispatchEvent(myEventToDispatch);
These three lines in your console should do the trick.
Checkout: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent for more options

found a solution, works in practice. The menu implementation on the site consisted of several nested divs and one input. None of these elements responded to the click () function. The solution below solved my problem and the next steps I needed.
<pre><code>
var MENU = IFrame.contentDocument.getElementsByClassName("class box menu")[0]; // getElementsById, getElementsByTag[0] ....
MENU = MENU.getElementsByTagName("div");
var MaxList = MENU[1].getElementsByTagName("input")[0];
if(MaxList != undefined)
{
if(MENU[0].textContent != "100 items")
{
// focus menu
MaxList.focus();
var e = new KeyboardEvent(
"keydown",
{
bubbles : true,
cancelable : true,
key : "ArrowDown",
char : "ArrowDown",
shiftKey : true
}
);
// scroll down the list
MaxList.dispatchEvent(e);
MaxList.dispatchEvent(e);
MaxList.dispatchEvent(e);
// choice
e = new KeyboardEvent(
"keydown",
{
bubbles : true,
cancelable : true,
key : "Enter",
char : "Enter",
shiftKey : true
}
);
MaxList.dispatchEvent(e);
}
}
</code></pre>
VKomyak (Volt_Nerd)

Related

Javascript How to force to click key?

force someone to click a key with javascript code.
For example:
$("#gameCanvas").mousedown(function(ev){
if(ev.which == 3)
{
this blank is for that want.
} });
I want to force users to click space button when they clicked right mouse as you see.
You could try a solution like the following one. This the link to the jQuery api doc.
$("#gameCanvas").mousedown(function(ev){
if(ev.which == 3)
{
// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event( "keydown", { keyCode: 32 } );
// trigger an artificial keydown event with keyCode 32
jQuery( "body" ).trigger( e );
} });

How to detect Click + [Shift, Ctrl, Alt] in reactjs click event?

I want to do some other things when user Click+[Ctrl], but it seems that I could not detect if user press Ctrl when clicking.
I copy the event object infos below.
bubbles : false
cancelBubble : false
cancelable : false
currentTarget : react
defaultPrevented : false
eventPhase : 2
isTrusted : false
path : Array[1]
returnValue : true
srcElement : react
target : react
timeStamp : 5690056.695
type : "react-click"
I can see the ctrlKey attribute in the arguments[0]-Proxy Object. But this object is unaccessable('Uncaught illegal access'):
[[Target]]
:
SyntheticMouseEvent
_dispatchInstances:ReactDOMComponent
_dispatchListeners:(e)
_targetInst:ReactDOMComponent
altKey:false
bubbles:true
button:0
buttons:0
cancelable:true
clientX:275
clientY:315
ctrlKey:false
Your click handling function would have a format as such:
clickHandler: function (event, value) {
event.stopPropagation();
// In that case, event.ctrlKey does the trick.
if (event.ctrlKey) {
console.debug("Ctrl+click has just happened!");
}
}
you can use this code below in your render() method
document.addEventListener('click', (e) => {
if (e.ctrlKey) {
console.log('With ctrl, do something...');
}
});
In the click event of this element you can check if at the moment of the click, a button (with keycode of ctrl in this case) is pressed down

javascript dispatchEvent Keypress, returns true , but input field is still empty

I need to trigger or say dispatchEvent KeyPress inside an Input box,
I have tried a lot with "initKeyboardEvent" , "initKeyEvent" , "createEvent", even I found similar question's answers but nothing seems to work, neither in firefox, nor in chrome (I think they may be deprecated), as
KeyboardEvent.initKeyEvent(), is deprecated.
like we have
document.getElemntByID('button').click();
I want to do something like:
document.getElemntById('email').keyPress(charCode('a'));
but unfortunately I am not able to make keypress work in any way.
I know it is possible in jQuery , but I want to do it in pure javascript, after all jquery uses Javascript in backend , so there must be a way , if I am not wrong.
====Update=========
I wonder
window.addEventListener('keydown', keyDown(), true);
function keyDown(){
alert('keydown');
}
var fireOnThis = document.getElementById('pwph');
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keydown', true, true, window, false, false, false, false, 72, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keydown', true, true, window, 1 );
evObj.keyCode = 72;
}
fireOnThis.dispatchEvent(evObj);
This code returns me true , and even the eventListner is catching this event, then why am I not able to see any text inside the input box?
====================update============================
This seems to work for everyone, but why does it leaves my text field empty, even after returning true?
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
I was trying to dispatch a keyPress event inside an Input element to pass the data-bind condition(KnockOut js) event , but unfortunately KeyPress didn't worked for me, Instead I used change event in place of it.
so I did this:
element = document.getElementById('idTxtBx_SAOTCS_ProofConfirmation');
element.value = '8885'; // this alone was not working as keypress.
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true); // adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);
so .value and change event together made, fake inputText or keypressed event successful.
i think so like you want to add event listener on input box
var element = document.getElementById("email");
document.getElementById("email").addEventListener("keypress", function() {
console.log("keypresh")
})
var evt = document.createEvent("KeyboardEvent");
evt.initEvent("keypress", false, true);
// adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);

simulate ctrl + click with javascript or jquery (to open a new tab without focus)

I am playing with the jquery event object but I am stuck as hell
I read the API https://api.jquery.com/category/events/event-object/ but it's not really helping here, I am not even sure it's a good lead to do that
Do you have any suggestion ( the problem is to do the exact ctrl + click on a link). I saw some posts about it but nothing seems to work on the recent browsers
very simple exemple :
<span id="toto">toto</span>
// The goal is when I click on #toto, I would like #inANewTab trigger
// in a new tab without focus. To do that I was thinking
// about replicate a ctrl+click event
$('#toto').click(function(){
???
})
Edit:
The Event object in jQuery has a parameter for ctrlKey, you could assign that as true, on click.
var e = jQuery.Event("click");
e.ctrlKey = true;
$('#id').trigger(e);
Reference: jquery trigger ctrl + click
In pure javascript, you can use the MouseEvent for that:
document.getElementById("todo").dispatchEvent(new MouseEvent("click", {ctrlKey: true}));
To programatically open a new tab you can do that:
const a = document.createElement("a");
a.setAttribute("href", "https://www.google.com/");
a.dispatchEvent(new MouseEvent("click", {ctrlKey: true}));
This is a non-jQuery version to simulate keyboard events. This works in both Chrome (WebKit based) and Firefox (Gecko based):
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
40, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
Or using jQuery, you can simulate by jQuery's event object:
jQuery.event.trigger({
type: 'keypress',
which: character.charCodeAt(0)
});

Close menu event in jQuery

I have a menu plugin in jQuery.
The menu is closed only when i click the inner circle of it...
www.tranceil.fm -> click the headphones
I want to close the menu by clicking anywhere, not just the inner circle
the header code is this
<script type="text/javascript">
jQuery(document).ready(function(){
var pieMenu = jQuery('#promo').pieMenu({icon : [
{
path : "/wp-content/themes/Tersus/images/piemenu/winamp.png",
alt : "Winamp",
fn : function(){('Click:: Plus');window.location.href = 'http://94.23.250.14:2199/tunein/tranceilfm.pls';return false}
}, {
path : "/wp-content/themes/Tersus/images/piemenu/vlc.png",
alt : "VLC Media Player",
fn : function(){('Click:: Plus');window.location.href = 'http://94.23.250.14:2199/tunein/tranceilfm.pls';return false}
},{
path : "/wp-content/themes/Tersus/images/piemenu/QuickTime.png",
alt : "Quick Time Player",
fn : function(){('Click:: Plus');window.location.href = 'http://94.23.250.14:2199/tunein/tranceilfm.qtl';return false}
},{
path : "/wp-content/themes/Tersus/images/piemenu/WMP.png",
alt : "Windows Media Player",
fn : function(){('Click:: Plus');window.location.href = 'http://94.23.250.14:2199/tunein/tranceilfm.asx';return false}
},{
path : "/wp-content/themes/Tersus/images/piemenu/popup.png",
alt : "נגן Popup",
fn : function(){jQuery("#popupplay").click();return false}
},{
path : "/wp-content/themes/Tersus/images/piemenu/iTunes.png",
alt : "iTunes",
fn : function(){alert('...בקרוב');return false}
}],
beforeMenuOpen: function(){
jQuery('<div id="shadow"></div>').css(
{
'position':'fixed',
'background-color':'#000000',
'opacity': 0.6,
'width':'100%',
'height':'100%',
'z-index' :999,
'top':0,
'left':0
}).appendTo('body');
},
beforeMenuClose: function(){
jQuery('#shadow').remove();
}
});
jQuery('#promo').click(function(){
if(jQuery('#'+pieMenu.id).css('display') != 'block') //if jpie is not visible
pieMenu.initMenu(760,150);
})
});
</script>
The click event in the JS file ->
//click event
jQuery('#'+idCore).live({
click: function() {
if(closable)
removeMenu();
},
contextmenu:function(e){
e.preventDefault();
}
})
Any thoughts?
Looks like you need to remove the pie0 div and the shadow div when the shadow is clicked, because they're being entirely generated/re-generated whenever they are brought on/back to the screen.
So just add this:
$('#shadow').on('click', function(event){
$('#pie0').remove();
$(this).remove();
});
Update: I just realized: because shadow is added dynamically after a user-event, and not present on documentready, you need to define it by attaching it to the body element, and delegating to a click on the shadow element, like this:
$('body').on('click', 'shadow', function(event){
$('#pie0').remove();
$(this).remove();
});
If you want to close it by clicking anywhere:
$(document).live({
....
});
The problem that you will face here is that this click will cause other clicks also to happen. For example, if the user clicks on some link or something, he will be redirected and also the menu will be closed. Moreover, since document is a top level element, events will never propogate FROM it, they will always propogate TO it. Even if such was not the case, live works in a way such that it handles events once they have propagated to the top
What you can do is, set it up in capture mode:
document.addEventListener('click', function(event) {
if(closeable) {
removeMenu();
event.stopPropogation();
}
}, true);
The true parameter at the end sets this event listener in the capturing mode, which will cause it to call the event handler of the highest order ancestor there is, which will be there for document. After calling that event, the event is then bubbled to the target. And within document's event handler, if we consume an event (we shall do it ONLY and ONLY if closeable is set), then we don't propagate it at all.

Categories

Resources