I have this code:
document.getElementById('auth-button').addEventListener('click', authorize);
When my page load I want to trigger that without clicking the button.
This is my view
When authorized button clicked this is the output
I want to auto click that button when my page load.
You can use addEventListener to the DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function() {
authButton.click();
}, false);
Full example:
https://jsfiddle.net/7q0gxehk/1/
you can use Document ready in jQuery, try this..
$( document ).ready(function() {
authorize();
});
or this in javaScript..
window.onload = authorize;
NOTE: The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
You could call the function authorize() on load of page using below code :
document.addEventListener("DOMContentLoaded", function(event) {
authorize();
});
You can register authorize as handler to be called when the page is fully loaded:
$(document).ready(authorize);
This requires jQuery. The same can be achieved without jQuery this way:
window.addEventListener('load', authorize);
It would be easier to tigger authorize function directly on page load using window.onload which is better than document.onload, see window.onload vs document.onload
window.onload = authorize;
However, if you are thinking about triggering click programmatically which is not suggested since it won't work properly across browsers e.g. Safari doesn't work at all
None of the other answers offered thus far seem to take something into account - that the registered handler may in fact need to be aware of it's place in the DOM.
We could for instance, have a number of buttons that all call the same handler, with that handler manipulating the surrounding DOM. Simply calling authorize when the page loads will not be sufficient.
I've chosen to use DIVs instead of BUTTONs to demonstrate that the .click() method still works.
A far better way is to actually click the button, using javascript.
#1 Not working
function byId(id){return document.getElementById(id)}
function allByClass(clss){return document.getElementsByClassName(clss)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
forEach(allByClass('mBtn'), addHandler);
function addHandler(elem)
{
elem.addEventListener('click', authorize, false);
}
alert('hit a okay to call authorize');
authorize(); // wont return from this call, since authorize relies on a valid 'this' value
}
function authorize(evt)
{
this.classList.add('clicked');
this.textContent = 'clicked';
}
.mBtn
{
border: solid 1px #555;
border-radius: 2px;
display: inline-block;
}
.clicked
{
color: #dddddd;
pointer-events: none;
}
<div class='mBtn'>Try me</div><div id='btn2' class='mBtn'>Or me</div><div class='mBtn'>Or even, me</div>
#2 - Does work
function byId(id){return document.getElementById(id)}
function allByClass(clss){return document.getElementsByClassName(clss)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
forEach(allByClass('mBtn'), addHandler);
function addHandler(elem)
{
elem.addEventListener('click', authorize, false);
}
alert('hit okay to click the 2nd button with javascript');
byId('btn2').click(); // will return from this call, since authorize relies on a valid 'this' value, and the btn gives it one.
}
function authorize(evt)
{
this.classList.add('clicked');
this.textContent = 'clicked';
}
.mBtn
{
border: solid 1px #555;
border-radius: 2px;
display: inline-block;
}
.clicked
{
color: #dddddd;
pointer-events: none;
}
<div class='mBtn'>Try me</div><div id='btn2' class='mBtn'>Or me</div><div class='mBtn'>Or even, me</div>
Use one of the following:
<body onload="script();">
or
document.onload = function ...
or
window.onload = function ...
Related
Would you please help me delay execution of my function until the content has loaded? I've streamlined my code to the essentials, bear with my typos:
function Phase1()
{
$(".Hidden").load("hidden.html");
$(window).load(Phase2());
/* I've also tried $(document).ready(Phase2()); */
/* and $(."Hidden").load("hidden.html",Phase2()); */
/* and window.onload... */
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
The Random class contains several items. On the first pass the alerts are never called (length is 0), on the 2nd iteration it's had time to load everything.
I see no errors in the console when executing.
I have a small and neat solution for your problem, all you need to do is,
Call a setInterval for very short span to check the element is present in DOM or not, if its not your interval will go on, once the element is present, trigger your functions and clear that interval.
code will look like this..
var storeTimeInterval = setInterval(function() {
if (jQuery('.yourClass').length > 0) {
//do your stuff here..... and then clear the interval in next line
clearInterval(storeTimeInterval);
}
}, 100);
The page will load the elements from top to bottom.
If you want your JS code to execute after all elements have loaded, you may try any of the following:
Move your script to the bottom of the page.
<html>
<head></head>
<body>
<!-- Your HTML elements here -->
<script>
// Declaring your functions
function Phase1()
{
$(".Hidden").load("hidden.html");
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
// Executing your functions in that order.
Phase1();
Phase2();
</script>
</body>
</html>
Bind your functions to document ready using Vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
Phase1();
Phase2();
});
Bind your functions to document using jQuery.
$(document).ready(function() {
Phase1();
Phase2();
});
I am using the FoundationPress theme (Wordpress Theme with the Foundation 6 from Zurb framework), and i'd like to ajaxify it. (using Ajaxify Wordpress Site plugin).
Now my problem is that most of the javascript that's on my website isn't working after an ajax load.
I have found that this is because most of the javascript in the foundation.js file is executed on document.ready, and that this event is not being triggered when loading a page with ajax.
I understand that it is not possible to trigger the document.ready event after page load. And after seeing multiple threads here, it appears the only solution is to create a new function with the code that's needed on document.ready and ajaxComplete.
BUT, Foundation has a lot of javascript files, and most of it is above my level of understanding. Is there any way to create a function that would automate this ?
EDIT I tried this. I need to pass jQuery as an argument or the code inside initialiseSticky will not work. It works for document.ready but not for ajaxComplete, any idea ?
jQuery(function($) {
console.log('document ready- sticky');
initialiseSticky($);
});
$(document).ajaxComplete(function ($) {
console.log('ajax complete- sticky');
initialiseSticky($);
}(jQuery));
function initialiseSticky($) {
//my code
}
Not sure about foundation.js but if you can make a variable, FooBar for example, assign the function() in $(document).ready() to that variable, and then on ajaxComplete call the variable/function again to "re-trigger" it, like below:
jsFiddle
var res = $('#result'),
bg = $('#bg-div'),
btn = $('#btnTest'),
i = 0, // just for demo to illustrate that it is changing
FooBar;
$(document).ready(FooBar = function() {
bg.delay(200).fadeIn(2000);
console.log('document is ready ' + i++);
});
// simulate ajaxComplete
btn.on('click', function() {
res.text('just dummy text here ' + i);
bg.fadeOut(500);
FooBar();
});
body { margin: 0; padding: 0 }
#bg-div { background-color: orange; width: 100%; height: 100%; position: fixed; z-index: -1; display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="bg-div"></div>
<button id="btnTest">Click Me</button>
<div id="result"></div>
I would like to disable a certain function from running as an onclick event.
Here, I would like to disable myfunc1, not myfunc2. Actually I want to disable myfunc1 from the whole page, but anyway this is the only thing that I need.
I have no control over the page and I am using userscript or other script injection tools to achieve this.
What I've tried:
Redefining the function after the page has loaded: I've tried adding an event listener to an event DOMContentLoaded with function(){ myfunc1 = function(){}; }
This seems to be working, but in a fast computer with fast internet connection, sometimes it runs before the myfunc1 is defined (in an external js file that is synchronously loaded). Is there any way that I can guarantee that the function will be executed after myfunc1 is defined?
Is there any way that I can 'hijack' the onclick event to remove myfunc1 by its name?
You should use event listeners, and then you would be able to remove one with removeEventListener. If you can't alter the HTML source you will need something dirty like
function myfunc1() {
console.log('myfunc1');
}
function myfunc2() {
console.log('myfunc2');
}
var a = document.querySelector('a[onclick="myfunc1();myfunc2();"]');
a.setAttribute('onclick', 'myfunc2();');
Click me
Or maybe you prefer hijacking the function instead of the event handler:
function myfunc1() {
console.log('myfunc1');
}
function myfunc2() {
console.log('myfunc2');
}
var a = document.querySelector('a[onclick="myfunc1();myfunc2();"]');
var myfunc1_;
a.parentNode.addEventListener('click', function(e) { // Hijack
if(a.contains(e.target)) {
myfunc1_ = window.myfunc1;
window.myfunc1 = function(){};
}
}, true);
a.addEventListener('click', function(e) { // Restore
window.myfunc1 = myfunc1_;
myfunc1_ = undefined;
});
Click me
Another way this could be done is using Jquery and setting the onlick propery on the anchor tag to null. Then you could attach a click function with just myfunc2() attached.
$(document).ready(function () {
$("a").prop("onclick", null);
$("a").click(function(){
myfunc2();
});
});
function myfunc1() {
console.log('1');
}
function myfunc2() {
console.log('2');
}
<a class="test" href="#" onclick="myfunc1();myfunc2();">Example</a>
You can see the codepen here - http://codepen.io/anon/pen/BLBYpO
Perhaps you are into jQuery.
$(document).ready(function(){
var $btn = $('button[onclick*="funcOne()"]');
$btn.each(function(){
var newBtnClickAttr;
var $this = $(this);
var btnClickAttr = $this.attr("onclick");
newBtnClickAttr = btnClickAttr.replace(/funcOne\(\)\;/g, "");
$this.attr("onclick", newBtnClickAttr);
});
});
Where in the variable $btn gets all the button element with an onclick attribute that contains funcOne().
In your case, this would be the function you would like to remove on the attribute e.g., myfunc1();.
Now that you have selected all of the elements with that onclick function.
Loop them and get there current attribute value and remove the function name by replacing it with an empty string.
Now that you have the value which does not contain the function name that you have replace, you can now update the onclick attribute value with the value of newBtnClickAttr.
Check this Sample Fiddle
After some hard work on the backend of my Web Application I noticed that the GetMeasure Request takes up to 10 seconds to finish. I decided to apply an overlay so a potential user won't get confused because nothing happens on the screen. No matter if the request is successfull or not the overlay should get removed after the call - so using the complete handler should be the best choice - at least I thought. I really don't get why but in opposite to the success handler the complete handler won't get called.
AJAX Request:
$_loadingCircle = $('<img id="loading" src="http://www.obergurgl.com/_images/layout/loading.gif"/>');
PopulateOverlay($_loadingCircle);
$.ajax({
url: 'CoDTracker/Home/GetMeasures',
type: 'POST',
dataType: "html",
data: {
buID: buid,
aID: aid,
lID: lid
},
success: function (data) {
$('#measures').html(data);
},
complete: function () {
$_overlay.remove();
}
});
The request ends with status 200 (successfull) but the overlay won't get removed. I'm sure that the request completed because my measures got filled into the page while the circle spins as crazy instead of disappearing.
Am I doing something wrong?
Edit:
Overlay-definition
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
Your $_overlay is defined incorrectly.
Please use:
$_overlay = $('div.overlay');
And please refer to jQuery Selectors for more information:
https://api.jquery.com/category/selectors/
The way to select a div with a particular class, is not to copy the entire <div class="">, but rather as I did in the example above.
EDIT: in fact, if you make this change, your PopulateOverlay will no longer work, so you should rather just select it without assigning it to a variable:
complete: function () {
$('div.overlay').remove();
}
Because overlay is appended in the DOM, you should remove it with .class:
complete: function () {
$('.overlay').remove();
}
First, if there's no error, and that's all your code, it should work fine.
Let's try to make an example, with a mimic function to mimic the behavior of ajax complete, we can write it like:
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
$_overlay.remove();
});
}
$(function() {
theWorks();
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I guess, that your codes, is inside another function, and you may call it many times, let's make a button, and click to trigger it:
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
debugger;
$_overlay.remove();
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
Now, if click the button before the previous pop out disappear, some popouts last forever.
Why? Because when you click again, your $_overlay will be assign to a newly created element, which means you lost the reference to the previous pop out, and when later the remove works takes action, it only remove the newest one, and all the following removes, are about to remove something that is not on the page, so you won't see effects, and older popouts remains.
We could fix it, by catch the current element in another variable when you're executing your codes. This would work if you expect many pop outs.
var $_overlay = null; // We assume you define it somewhere, and it's visible to all your functions.
function PopulateOverlay($content) {
$_overlay = $('<div class="overlay">');
$content.appendTo($_overlay);
$_overlay.appendTo('body');
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
// Cache the current overlay, or simply move $_overlay here, if no other using it.
var $_curOverlay = $_overlay;
mimic(function() {
$_curOverlay.remove();
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: block;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
Or as what Laurens Swart suggest, simply toggle the state if you only need one pop out at a time.
var $_overlay = $('.overlay');
function PopulateOverlay($content) {
$_overlay
.empty() // Clear previous
.append($content) // Append the content
.show(); // Make it visible.
}
// See this as an ajax call with 2 sec delay.
function mimic(cb) {
setTimeout(cb, 2000);
}
function theWorks() {
$someEle = $('<div class="example">example</div>');
PopulateOverlay($someEle);
mimic(function() {
$_overlay.hide(); // Instead of remove, we make it hide, so we can reuse it later.
});
}
$(function() {
$('#click').on('click', theWorks);
});
.overlay {
display: none;
width: 100px;
height: 100px;
background-color: black;
}
.example {
color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click</button>
<div class="overlay"></div>
i am trying to do post AJAX request only once after color is set for more than 2 seconds.
[DEMO FIDDLE]
fiddle
in the fiddle i want AJAX call to be fire only once after color is selected.
i don't want AJAX call to done on every click
how to do that?
As you want it to fire only once, bind .one() instead of .on() to the element. This will make the event execute only once.
And for delay, use setTimeout().
You can simply add a flag to check if your code ran before.
var timeout;
var executed;
var arry = ['red', 'blue','orange', 'green'], i=0, len= arry.length;
$('#element').on('click',function(){
$(this).css('background',arry[i++]);
if(i===len){i=0;}
if(!executed){
clearTimeout(timeout);
timeout = setTimeout(function(){
alert("executed");
executed = 1;
}, 2000);
}
})
#element{
width:50px;
height:50px;
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
Demo
This can be done by just adding a condition in your click event as below
$(document).on("click", "#element", function () {
if ($('body').data("isServerHit") === undefined) {
$('body').data("isServerHit", true);
setTimeout(function () {
// Write the code for ajax call here
alert('server will hit now');
}, 2000);
}
});
For more details on $('body').data("isServerHit", true);, visit save data (in jquery)
Hope this helps :)