javascript to auto click a link not working - javascript

hello im trying to get a script to run so that a link auto clicks after certain amount of time
on familyoffices.com the link is the "we are online" graphic at the bottom right
im using
<script type="text/javascript">
$(document).ready(function() {
setTimeout(function() {
$('#desginstudio-button-image-desktop').click();
}, 300);
});
</script>
unfortunately this isn't firing off....anyone know how i can achieve this?

Try using
<head>
<script>
function haveclicked(){
document.getElementById('myLink').click();
}
</head>
<body onload="setTimeout('haveclicked();',3000);">
<a id="myLink" href="http://www.google.com" target="_blank">GOOGLE</a>
</body>

Consider this from the MDN.. You need to create an event to do this correctly.
function simulateClick() {
var evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
});
var cb = document.getElementById("checkbox"); //element to click on
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
document.getElementById("button").addEventListener('click', simulateClick);
<p><label><input type="checkbox" id="checkbox"> Checked</label>
<p><button id="button">Click me</button>

Instead of
$('#desginstudio-button-image-desktop').click();
Try using
$('#desginstudio-button-image-desktop').trigger('click');

You can try to first locate the iframe and the element in it --
var frame = document.getElementById(/* your frame id*/),
button = frame.contentDocument.getElementById(/* your button id*/);
Then dispatch a synthetic event --
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));

Some browsers/versions don't support using click() to trigger a click event. Try using .trigger('click') instead

Related

Actually do default after preventing default

I want to prevent default behavior of a link (a) then do the default behavior, let's say open open a link in a new window.
Here is some HTML code:
<a href="somewhere" target="_blank" id="mylink">
And the JS code:
document.getElementById('mylink').addEventListener('click', function (e) {
e.preventDefault();
axios.post('options', new FormData(document.querySelector('#myform')))
.then(function(){
// Here I want to do what the link should have done!
});
});
I know I can do something like this:
window.open(e.target.href);
But it's not an option because the browser consider this as a popup. And I don't want to rewrite something in JS, just consider the link as usual: this link has to do its default behavior (which was prevented).
Is there a way to do this?
Here is some idea:
var openingPopup = false;
document.getElementById('mylink').addEventListener('click', function (e) {
if(!openingPopup){
e.preventDefault();
axios.post('options', new FormData(document.querySelector('#myform')))
.then(function(){
// make sure this would not run twice
openingPopup = true;
document.getElementById('mylink').click();
});
}else{
// skipping this only for one time
openingPopup = false;
}
});
This way,
you run the popup opener click handler once,
then prevent the others,
trigger the click event again manually,
this time do nothing, but allow others to run.
As per #Electrox-Qui-Mortem 's suggested link, after you complete your pre-process(es), you can remove the event listener and call the click again.
(relevant MDN link: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener )
const anchor = document.getElementById('anchor');
anchor.addEventListener('click', test);
function test(e){
e.preventDefault();
alert('test');
if( true ){
console.log( this );
this.removeEventListener('click', test);
this.click();
}
}
<a id="anchor" href="https://www.google.com">Test</a>
It's got wonky performance inside code testing tools (like JSfiddle and CodePen) -- you would have to test it in your actual application to make sure if it works appropriately for your use case.
I've only had good results with removeEventListener when referencing an outside function as the "listener" func. In this case test()
In a more "native" way you could create a new "click" event which is not cancelable and trigger it against the same element.
var anchor = document.querySelector('#target');
function triggerClick(target) {
var newClick = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: false
});
target.dispatchEvent(newClick);
}
anchor.addEventListener('click', function(e) {
e.preventDefault();
if(e.defaultPrevented) {
alert('Prevented!');
triggerClick(anchor);
}
else {
alert('Not prevented');
}
});
Click me!
Here the key is the cancelable: false in the new event created in the function triggerClick(target), which bypass the e.preventDefault().
In the embedded example on StackOverflow it doesn't work, but here's a JSFiddle!

How to trigger MouseDown via PhantomJS?

I tried:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent("mousedown", true, true);
jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0].dispatchEvent(clickEvent);
but it just fails to trigger the action on the site.
no error returned.
This is how you programmatically trigger a click on a DOM element with a "mousedown" event. To answer your question, you need to have two things in your source code:
event listeners to detect the clicks
and
commas between your multiple selectors in your jQuery line.
Please run the snippet below, which shows the modified jQuery line and the listeners running correctly.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// You must have event listeners to see if anything is actually happening. For example, here I will add only a listener to the first element:
jQuery(".left-rail-facets")[0].addEventListener('mousedown', function(e) {
jQuery(".left-rail-facets")[0].innerHTML = "I have received a click.";
}, false);
// Now here is the code from your question. Please see how I have commas instead of spaces in my jQuery selector:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('mousedown', true, true);
jQuery('.left-rail-facets,.facet-list,.facet.CS,.suggestion[data-value="B"],a')[0].dispatchEvent(clickEvent);
});
</script>
</head>
<body>
<h1>I am a Webpage</h1>
<p class="left-rail-facets">I have not received a click.</p>
<p class="facet-list">I have not received a click.</p>
<facet class="CS">I have not received a click.</facet>
<p class="suggestion" data-value="B">I have not received a click.</p>
I have not received a click.
</body>
</html>
You will need to use the document.createEvent and event.initMouseEvent:
var element = document.querySelector('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a');
//or var element = jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0];
var elementRect = element.getBoundingClientRect();
var mouseEvent = document.createEvent('MouseEvents');
mouseEvent.initMouseEvent('mousedown', true, true, window, 0, elementRect.left, elementRect.top);

Propagation of custom events

I expect my CustomEvent to be propagated from document to all the DOM elements.
For some reason, it does not happen. What am I doing wrong?
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
By default Custom Events are not bubbled.
Reason being, Custom Event definition says:
let event = new CustomEvent(type,[,options]).
Options have a flag : bubbles, which is false by default, we have to enable it.
Following will fix your code
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchEvent(new CustomEvent("myEvent",{detail:null,bubbles:true}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
You have to dispatchEvent the event on the element you want the event 'triggered' on. It will then propagate down and back up the DOM
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
myDiv.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
fiddle: https://jsfiddle.net/yrf9cvr3/
How propagation works: The event starts at the document and works it's way down to the element it was dispatched on (You can capture the event going this way using onCapture flag). Then goes back up to the document. Because you are dispatching on the document the event doesn't really go anywhere, only document see the event.
This is currently not possible as stated in the MDN doc https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#event_bubbling, event can only bubble from child to ancestors, i.e. upward for now.
The best way you can achieve this is use document.querySelector to target the element(s) you want to dispatch the event to, then dispatch as needed.
document.querySelector("#myDiv").dispatchEvent(customEv);
Try this one. Use document.querySelector and specify the events you want to track. Click the button or type some text in the text box
<html>
<script>
function onLoad() {
// var myDiv = document.getElementById("myDiv");
// myDiv.addEventListener("myEvent",function(){alert("Yes!");});
// document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
var myDiv = document.querySelector("#myDiv");
myDiv.addEventListener("click", myEventHandler, false);
myDiv.addEventListener("change", myEventHandler, false);
}
function myEventHandler(e)
{
alert('Element was '+e.target.id+'\nEvent was '+e.type);
}
</script>
<body onload="onLoad()">
<div id="myDiv">
<input type="button" id= "Button 1" value="Button 1"><br>
<input type="text" id="Text 2">
</div>
</body>
</html>
I am posting some solution, not really an answer.
This will propagate a custom event to all the elements in the DOM.
<html>
<script>
document.dispatchCustomEvent = function(event) {
function visit(elem,event) {
elem.dispatchEvent(event);
var child = elem.firstChild;
while(child) {
if(child.nodeType==1) visit(child,event);
child = child.nextSibling;
}
}
visit(document.documentElement,event);
}
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchCustomEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
Going with the extreme. Events propagate down to the element they are dispatched on and back up... So in order to trigger an event on any and essentially all elements (since it is unknown which elements need the event) you can find the "ends" of all of the "branches" of the DOM and dispatch events to them.
jQuery makes it easy to select the end of the branches
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent", function() {
alert("Yes!");
});
$(':not(:has(*))').each(function(i, el){
el.dispatchEvent(new CustomEvent("myEvent", {
detail: null,
bubbles: true
}));
});
}
https://jsfiddle.net/dkqagnph/1/
Using this will ensure EVERY DOM element (attached to the body) gets the event (assuming that no element stop propagation itself) and thus making there be no need to know which elements are listening or care about the event. This doesn't dispatch to every individual element, as that would be overkill, but just the end and lets bubbling do it's thing.
NOTE: elements with more than one child will get the event more than one time. You may want to have a way to ensure that your code does run more than once or does not care if it runs more than once.

How to enable a button after loading the page

I have to disable a button when the page is loading.
How do I enable the button after fully loading the page, using jQuery or JavaScript?
Disable any button from the beginning:
<input type="button" disabled="disabled" />
And add the enable to window ready function
$(document).ready(
function(){
$("input[type=button]", "<input[type=submit]", "input[type=reset]").each( //add more selector here if you want
function(){
if($(this).attr("disabled"))
$(this).attr("disabled", false); //enable button again
}
);
}
);
Or you can do
<body onload="load()">
and
<script type="text/javascript">
function load()
{
document.getElementById("buttonID").disabled=true;
}
</script>
add a disabled property for the button and in the script, document ready function remove disabled function.
$("#buttonID").prop('disabled',false)
This is based on #Bang Dao's answer but using native JavaScript.
Disable the button from the beginning:
<button id="button" disabled>A button</button>
And then listen for the DOMContentLoaded event on document:
document.addEventListener('DOMContentLoaded', function() {
const button = document.getElementById('button');
button.disabled = false;
});

How to close a javascript menu

I'm creating pulldown menus that must be clicked on to open. This code lets the user opening menus just fine. The only problem is I haven't figured out how to close the menus yet by clicking outside the menus. I tried adding the "document.onclick" shown, but it takes effect even in the menus.
I think I need to prevent document.onclick from being captured by other elements, but am not sure how to do this cross-platform. Can someone please show me how?
<script type="text/javascript">
var lastOpenedMenuId = null;
function showMenu(menuId) {
if (lastOpenedMenuId != null && lastOpenedMenuId != menuId) {
hideLastOpenedMenu();
}
setMenuVisibility(menuId, 'visible');
lastOpenedMenuId = menuId;
}
function hideMenu(menuId) {
setMenuVisibility(menuId, 'hidden');
}
function hideLastOpenedMenu() {
if (lastOpenedMenuId != null) {
hideMenu(lastOpenedMenuId);
}
}
function setMenuVisibility(menuId, visibleOrHidden) {
var menuElement = document.getElementById(menuId);
menuElement.style.visibility = visibleOrHidden;
}
document.onclick = hideLastOpenedMenu;
</script>
<div onmousedown="showMenu('foodmenu')"><a>FOOD</a></div>
<div id="foodmenu" onmouseup="hideMenu('foodmenu');">
Meat
Tofu
</div>
Thanks in advance.
I have made some progress and have reformulated the question here:
How to stop onclick event in div from propagating to the document?
Depending on whether you have a page layout like this:
<body>
<div id="menu"><!--Menu Stuff--></div>
<div id="main"><!--Main page stuff--></div>
</body>
you could put the onClick handler to close the menu on the div with the id "main" which should work
Someone pointed me to a solution that uses addEventListener. Say, the div is the menu. This code allows the user to click on the document outside the div to do something, such as close the menu. Clicking on the div (say, on a link) will not propagate to the document.
<head>
<script>
function menuHandler(event) {
alert("div clicked");
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
document.onclick = function() {
alert('document clicked');
};
function addListener() {
var foodMenuElement = document.getElementById('foodmenu');
if (foodMenuElement.addEventListener) {
foodMenuElement.addEventListener('click', menuHandler, false);
} else {
foodMenuElement.attachEvent('onclick', menuHandler);
}
}
</script>
</head>
<body onload="addListener()">
<div id="foodmenu" style="border: 1px solid red;">Click inside this div</div>
or click outside the div.
</body>
Note that the third argument "false" to addEventListener means "fire the event during the capturing phase", but the value doesn't matter because the event propagation is canceled in menuHandler.
This solution works, but I'd like to do the same thing more simply, without addEventListener, so have posted a question at How to stop onclick event in div from propagating to the document?

Categories