Automatically click also 2nd button when click 1st button - javascript

I have problem in the click buttons. What i need is to automatically clicked 2nd button when i click the 1st button.. I have created a sample code which is not working
HTML
<button id="button1" class="btn btn-success">1st button</button>
<a id="button2" class="btn btn-success" href="google.com">2nd button</a>
jQuery
jQuery(document).ready(function() {
jQuery('#button1').click(function () {
jQuery('#button2').click();
})
});
Here's my jdfiddle
https://jsfiddle.net/wj8pb9sf/

I've had this code snippet for quite some time and it has proven itself to be very valuable in these situations:
// Simulate event
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
It doesn't rely on jQuery and allowes you to simulate a bunch of usefull events. Simply do: fireEvent(document.getElementById('button2'), 'click');.

$("#button1").click(function(){
$("#button2").click();
});
And also you can't give href in button.

Related

Perform DoubleClick on element that have that

looks here:
that from One page that show me that element have event of doubleclick "dblclick"
but when i try to perform it from console:
dblclick is not a method, it is a type of event.
Let's say you have a button, and you wanted to manually fire that event. You could do so like this.
<button id='myButton'>Click Me!</button>
Now you can do this
var evt = new Event('dblclick');
var button = document.getElementById('myButton');
// This is where the magic happens
button.dispatchEvent(evt);
This manually fires the dblclick event.
You must call 'dispatchEvent' on a dom node, and it takes an 'Event' object.
For your use case, just replace the 'button' element with your own 'a' variable, and it should work as expected.
That answer works as well:
thank you both guys
noahnu and epascarello
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("dblclick", true, true);
} else {
event = document.createEventObject();
event.eventType = "dblclick";
}
event.eventName = "dblclick";
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventType, event);
}

Trigger click event of plus button on google plus

I cant trigger event onClick of plus button in Google plus
I have try with a method:
But it didn't work.
The code I tried
$(".mUbCce.fKz70d.GsLz7c.teCjMb.M9Bg4d").click()
I also noticed that when my mouse over the plus button, the mouse icon change to "hand-icon" but, I didn't find any CSS cursor for it.
Is there any magic from google ?
Thanks
Try this: Define a function fireEvent() like this:
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
And call
fireEvent($0,"mousedown")
fireEvent($0,"mouseup")
with $0 is the element you want to click

How do I prevent the user from typing new lines in a contentEditable element?

I made my div element contentEditable so that the user can edit its contents:
<div contentEditable='true' id='myDiv'>
This content can be edited.
</div>
However, I'd like to prevent the user from typing new lines into the div element. I've tried preventing the default action of keydown events to no avail:
var container = document.getElementById('myDiv');
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
container.blur();
e.preventDefault();
return false;
}
return true;
}
myDiv.addEventListener(
'keydown', tryToPreventNewLines);
myDiv.addEventListener(
'change', tryToPreventNewLines);
JSFiddle: http://jsfiddle.net/pwmspdm4/
In this case, the user can produce several new lines by hitting the enter key while within the div and not letting go of the enter key.
The problem seems to be the container.blur() call; if you move that out of the handling of the event with a setTimeout, the code works (prevents the user creating a newline, and blurs the container):
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
e.preventDefault();
setTimeout(function() {
container.blur();
}, 0);
return false;
}
return true;
}
Updated Fiddle
Of course, I'm assuming you want to blur the container when they press Enter. If not, just remove that line entirely.
Tested on Chrome, Firefox, and IE11.
Below you note that on Chrome, holding down Enter continues to add newlines, even with the above. The only way I see to prevent that is to control the contentEditable property:
var container = document.getElementById('myDiv');
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
e.preventDefault();
this.contentEditable = false; // No longer editable
this.blur(); // Remove selection box on Firefox
return false;
}
// Removed the `return true;` here; it was a no-op
}
function enableEdit() {
this.contentEditable = true; // Make it editable
this.focus(); // And put the cursor in it
}
// Just for max compatibility, added the third argument below;
// some browsers still require it
myDiv.addEventListener(
'keydown', tryToPreventNewLines, false);
myDiv.addEventListener(
'change', tryToPreventNewLines, false);
myDiv.addEventListener(
'click', enableEdit, false);
Updated Fiddle

How to detect control+click in Javascript from an onclick div attribute? [duplicate]

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

XUL textbox addEventListener

I'm trying to detect when a user hits escape or enter when in a xul textbox (firefox extension). But the following code doesn't seem to work. Any assistance would be much appreciated.
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function keyPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
// do something
break;
case KEY_ESCAPE:
// do something
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);
Are you running this script before the textbox has been inserted in the document? This example works fine for me:
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"><![CDATA[
window.addEventListener("load", function() {
const KEY_ENTER = 13;
const KEY_ESCAPE = 27;
function keyPressed(e) {
switch (e.keyCode) {
case KEY_ENTER:
alert('enter');
break;
case KEY_ESCAPE:
alert('escape');
break;
default:
alert('default');
break;
}
}
var textbox = document.getElementById("mytextbox");
textbox.addEventListener('keypress', keyPressed, true);
alert('there');
}, false);
]]></script>
<textbox id="mytextbox" value="stuff"></textbox>
</window>
I'm also a little curious why you're passing true as the capturing argument when adding the listener. Generally you want to do stuff in the bubbling phase when handling events, not the capturing phase (i.e. after listeners on more-specific descendants of the element where you're listening have been called).

Categories

Resources