I've been endlessly looking for a working way to automate a mouse click on a specific element using javascript (I'm making a user-script). The structure is like the below:
<div id="elementContainer">
<div class="item1" style="width: 50px; height: 50px;">AutoClick Here!</div>
</div>
item1 is the thing I want to automate a click on. I've tried lots of approaches, e.g. getting the element and creating/initialising/dispatching a 'click' event on it, calling .click() on it etc, but to be honest I'm new to javascript and don't hugely know what I'm doing!
I can happily get the element and make changes to it (like changing the innerHTML), but want to be able to simulate/automate a click on it too. I would be very grateful for any advice on how to proceed.
Many thanks in advance!
Calling .click() on the element should work just fine.
var container = document.getElementById('elementContainer'),
innerDiv = container.getElementsByClassName('item1');
innerDiv.click();
That said:
The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.
Non–Gecko DOMs may behave differently.
When a click is used with elements that support it (e.g. one of the INPUT types listed above), it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an A element to initiate navigation as if a real mouse-click had been received.
Have you bound any click event handlers to that <div>?
Read this: http://www.howtocreate.co.uk/tutorials/javascript/domevents
Related
I have a row of <a> elements which have onclick handlers:
<a onclick="selectCoin('MER');">
<div id="MER">
...
</div>
</a>
The interior of the <div> child gets overwritten continuously to update some text inside the buttons. The updating is done by querying the #MER selector, and assigning to innerHTML. I noticed that the onclick handlers don’t always run if the <div> element is being updated in the background. Oftentimes, I have to click it two or three times before the onclick hander actually gets invoked. If I make the <div> elements static, the onclick handlers run consistently and reliably.
Why does updating the <div> child cause the onclick handler to stop working consistently? How do I fix this issue, while still updating the contents of the button?
To generate a click event, an element must receive a mousedown followed by a mouseup.
If the element goes away after the mousedown and is replaced with a new one, the click event is not sent.
You could do your own mousedown/mouseup detection on the <a> element, but if nothing inside the element is really clickable, you can disable mouse events on the child elements, so that they all occur on the <a> element
on your "MER" div:
style="pointer-events:none;"
Working fiddle:
https://jsfiddle.net/8h17rcpz/
click events are only generated if a mousedown and mouseup pair of events are fired consecutively on the same element, which is not going to happen if it gets swapped between down and up events.
The simplest solution would be to replace onclick in HTML source with onmouseup. What side effects or undesirable behavior that might produce is not possible to assess from the information provided.
I'm implementing an autocomplete/combobox in dart. I'm using two elements for this, a <input type="text"> and a <ul> for the suggestions. I want to hide via css style display: none whenever the user leaves the input box. This works when using onBluron the input element.
If the user tries to click an item in the <ul>, the input looses focus and the <ul>is hidden before the click event on the <li> is run.
_listElement = new UListElement();
_textElement = new TextInputElement()
..onBlur((e) => setDisplayToNone(_listElement)); // hide element
I noticed that a jQueryUI implementation does not have this issue and I can not figure out how they detect when to hide the suggestion box. see https://jqueryui.com/autocomplete/
What alternate way can i use to hide the <ul> without hiding it on _textElement.onBlur?
If it helps, the two elements are always wrapped by a <div>. I'm looking for a dart-only solution, although vanilla-js answers that I can rebuild in dart are also appreciated.
Please look at events sequence:
input.focus
li.mousedown
input.blur
li.mouseup
li.click
So you might setup a flag variable, turn it up on li.mousedown, check it on input.blur and decide if you need to hide the list, and then turn it down on li.click
So I have a simple dropdown in my code that I attach a click hander to, like so (code is technically typescript)
this.highElement.click(() => {
console.log(event);
});
This event is triggered both when I click the select box AND when I click one of the options (Here's a Js fiddle that demonstrates what I mean https://jsfiddle.net/Kolichikov/zmdL6q2d/). What I would like ideally is for the event to only fire when I click the select box itself, not the resulting list of items.
I tried setting a delegated event for the option this.highElement.on("click", "option", () => { console.log("option!"); });, but that didn't work.
I have noticed that the MouseEvent properties are different (the mouse coordinates aren't populated when an item is clicked), but this seems like a browser implementation that could change (maybe?).
Is there a way to properly differentiate between the two events?
I'll give you 2 options, you pick the one it's best for you:
First you can differentiate between the 2 events like this:
$("#selectItem").click(function(event){
if (event.target.id == 'selectItem')
console.log(event)
});
the event has a different target when it returns from clicking in select and from choosing an option.
But I think it would be much clearer if you used the change event
$("#selectItem").change(function(event){
console.log(event)
});
it fires only when you select an item. Depending on what you need this could be better.
EDIT
Checkingwhat #libzz said, I notice that the first part of the above response is wrong. I didn't edit it because the OP accepted the answer as is and I'd be changing the code that lead to his decision.
But as #libzz said, the event when fired has always the same id.
What I also noticed now is that the click event only fires when an option is clicked, not when the select box is clicked. That levels the onclick with the onchange event. They basically do the same thing in this case.
So in order to make code clearer, the best would be using only onchange event for selects.
I have a <form> containing two text <input>s side-by-side. When both of these inputs lose focus, I want to do some stuff (send an Ajax request to server and replace them with something else in the DOM). However if I click or tab from one of the inputs to the other, I don't want to do those things.
Setting an onBlur event handler on the <form> element works fine using my setup, but there doesn't seem to be any way to determine if the other form input is my next target. If I examine document.activeElement in my handler, it points to the <body> element (in Chrome) at that point. Only afterwards does it change to the other input.
Is there any way to reliably do what I'm asking? Solutions involving jQuery or other libraries are fine.
So it turns out that event.relatedTarget was what I was looking for - this will return the DOM node receiving focus on a blur event, so it's just a matter of setting a conditional to see if it matches the other field.
However, while this works great in Chrome, relatedTarget currently isn't implemented properly in other browsers. Apparently there's a couple of workarounds:
In IE11, document.activeElement does actually get set to the receiving element at the time the event fires, so you can use that.
In Firefox, apparently event.explicitOriginalTarget can be used instead.
Try ..
Set a global variable that stores what you last blurred from. Call it x.
Set a blur event on all elements, and set x to the last element you blurred from.
Set a focus event on all elements, and if x is not one of your two elements, then run your script.
Give to them both ids, like this:
<input id="id1" />
<input id="id2" />
Then, with jQuery, you can call blur() nested with the two ids.
$('#id1').blur(function(){
$('#id2').blur(function(){
//do your thing
});
});
I've encountered a weird issue - accessing any DOM element's outerHeight, or simply logging that element to browser's console in a blur event seems to cancel the click event that caused the blur - when some special criteria is met.
Here's what I'm trying to do:
There are 2 inputs, first is initially visible, the other hidden
When the first input receives focus, the 2nd input will be shown
When the 2nd input receives focus, it remains shown
When both inputs lose focus, and none of them are focused, the 2nd input will be hidden
However, it seems that when I simply try to do something like $('body')[0].outerHeight in my blur event handler, the second input never receives the click or focus. Since it's too much to simply write down, here's a link to JSFiddle that demonstrates the issue: http://jsfiddle.net/7K2Ha/3/
Note - it happens the same with plain JS
Can anybody explain why this happens and are there ways around this?
Firstly, you bind focus/blur events to all .jq inputs. And then you add next event handlers (which means, that all of them will be executed - including the first one, which removes the has-focus class).
Check this fiddle, line 20: fiddle here.
$('#input3').unbind('blur').on('blur', //...
The problem is not specific to offsetHeight, and I believe if you comment out that line you don't get the effect simply because the browser will not call an empty function block for performance/optimizer reasons.
It seems to come down to the execution order of the events (especially problematic when more than one jquery event of the same type is wired up).
Check out what happens when you wire up the blur/mouseover/etc. events that all $('input.jq') elements have in common at the very end: http://jsfiddle.net/7K2Ha/6/
All I did was move the topmost javascript block to the bottom, and suddenly it works. In that case, the focus event seems to occur before the blur event. Notice how before the focus would never be called.
As a more robust solution, I'd only work with one event that covers both:
$('input.jq')
.on('focus', function() {
// get focus'ed elements parent
var thisParent = $(this).parent('div')
thisParent.addClass('has-focus');
// get all other parents
var otherParents = $('input.jq').parent('div').not(thisParent);
otherParents.removeClass('has-focus');
})
See updated JSfiddle.