I have a javascript that tries to get the information from the localStorage. Either i haven't fully understood window.onload or something else is faulty.
Thanks in advance!
onClickJs.js
function onClickLight() {
alert("OnClick Log " + window.onload);
window.onload = function (){
var statusPub = document.getElementById("result").innerHTML = localStorage.getItem("statusPub");
console.log(statusPub);
}
index.jsp
<script>
function load() {
console.log("load event detected!");
}
window.onload = load;
</script>
<button type="lightButton" onclick="onClickLight()">Light</button>
By the time you click the button, the window load event has already fired. So assigning a function to window.onload at that point is useless, the function will never be called.
If you want to do the work that function is doing, just...do it:
function onClickLight() {
var statusPub = document.getElementById("result").innerHTML = localStorage.getItem("statusPub");
console.log(statusPub);
}
Related
I've no idea if this is the right way to do what I'm trying to do (I have 0 experience with jQuery/Javascript):
window.onload = function () {
var Btn = document.getElementById('fmm-payment-btn');
Btn.onclick = function () {
gtag_report_conversion();
}
}
The gtag_report_conversion() looks like this:
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-URLHERE',
'transaction_id': '',
'event_callback': callback
});
return false;
}
Basically, I'd like to make sure that the function gtag_report_conversion() is executed when users click on fmm-payment-btn (to track conversions in Google Ads).
I tried this in a slightly different way using document.getElementById("fmm-payment-btn").onclick = function() but I kept getting an error, Uncaught TypeError: Cannot set property 'onclick' of null. I understand the method above should work better, but having no experience I cannot tell.
Would appreciate any feedback. :)
window.onload doesn't mean that the DOM is loaded.
If you want to be sure that the button is rendered you should use
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
document.getElementById("fmm-payment-btn").onclick = function(){}
// Or
document.getElementById("fmm-payment-btn").addEventlistener('click', function(){})
// Or even cleaner
document.getElementById("fmm-payment-btn").addEventlistener('click', gtag_report_conversion)
});
The JS below runs accordingly, but it never hits the last function (showAllTabIdRedirect). Any idea why? Is it my syntax? I am trying to run the first function that grabs the primary tab id and then use that to pass along some other functions. In the end, I would redirect the user as well as refresh a specific tab.
<script>
function refreshDetailsTab() {
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var formsId;
var currentUrl = window.location.href;
if (currentUrl) {
formsId = currentUrl.split('?formId=')[1];
} else {
return;
}
window.location = '/' + formsId;
debugger;
};
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var focusDetailSubtabRedirect = function showTabIdRedirect(result) {
// window.onload = function showTabIdV1(result) {
//alert('2222');
var primaryTabID = result.id;
sforce.console.getSubtabIds(primaryTabID , showAllTabIdRedirect);
debugger;
}
var showAllTabIdRedirect = function showAllTabIdRedirect(result2) {
// alert('33333');
var firstSubTab = result2.ids[0];
sforce.console.refreshSubtabById(firstSubTab, false);
debugger;
//alert('Subtab IDs=====: ' + result.ids[0]);
};
window.onload = refreshDetailsTab;
</script>
You can check for successful completion of those methods. It's possible 'getSubtabIds' was at halt for some reason and that would cause the failure of calling the callback function 'showAllTabIdRedirect '.
See the documentation here for getSubtabIds
I think it has something to do with the window.location triggering first. It redirects the user before the other JS can load.
I am executing setTimeout function in a page which loads via ajax call. but if i click the link to load the page again, i afraid the last setTimeout call still continues and the number of intervals of the calls set by setTimeout executes multiple times.
tried this is the remote page:
var RefreshInterval = null;
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
RefreshInterval = null;
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
declare var RefreshInterval = null; outside of page loaded by ajax and use this code on the page:
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
if i don't want to declare it in parent page, here is the solution i found:
//Clear previously loaded calls if exists
try{ clearTimeout(wifiRadarRefreshInterval); }catch(e){}
var wifiRadarRefreshInterval = null;
function somefunction(){
....
setNextRefresh();
}
function setNextRefresh() {
try{
clearTimeout(wifiRadarRefreshInterval);
wifiRadarRefreshInterval = null;
wifiRadarRefreshInterval = setTimeout('somefunction();', 20*1000);
}
catch(e){
console.log(e.message + e.stack);
}
}
Do not use this
var RefreshInterval = null;
clearTimeout(RefreshInterval);
You are actually assigning a null and then trying to clear it. Which will not work, The timeout must be cleared by using the clearTimeout and by passing the variable which was assigned to the setTimeout. Here you will end up passing a null so the timer is never cleared.
Here is a small sample which will demonstrate a fix to your problem JS Fiddle
So insted of setting the variable to null and then trying to clear it, Just check if the variable is not defined and if it is defined clear it, else move on. Use the code below, Also you must remove the top two lines as mentioned
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
Click on the button say like 4 times, The output should be printed only once. That is if the ajax call is made 4 times the set time out must execute only once. Check below snippet for demo
var clickCount= 0; // just to maintain the ajax calls count
function NewPageSimilator(clicksTillNow) { // this acts as a new page. Let load this entire thing on ajaX call
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
function setNextRefresh() {
window.RefreshInterval = setTimeout(printTime, 3000); //20*1000
}
function printTime() {// dumy function to print time
document.getElementById("output").innerHTML += "I was created at click number " + clicksTillNow + '<br/>';
}
setNextRefresh();
}
document.getElementById("ajaxCall").addEventListener("click", function() { // this will act as a ajax call by loading the scripts again
clickCount++;
NewPageSimilator(clickCount);
});
document.getElementById("clear").addEventListener("click", function() { //reset demo
clickCount = 0;
document.getElementById("output").innerHTML = "";
});
<p id="output">
</p>
<button id="ajaxCall">
AJAX CALL
</button>
<button id="clear">
Clear
</button>
My first code working but second code not working after adding () parenthesis after myFunction. What is the reason?
Code1
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction;
</script>
<h3 id="status"></h3>
Code 2
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
In first case you're assigning the reference of the function which will be used in callback.
In your second case you're assigning the value that is being returned by the function which is in this case undefined as you're not returing anything.
window.onload or any event handler for that matter, expects a function reference to be executed on callback.
window.onload is an event handler and must be a function, not the result of function. of course you may leave parenthesis, but in this way your function myFunction should return another function
<script type="text/javascript">
function myFunction(){
return function() {
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
The goal
Send true or false when window is closed.
The problem
When I click on a button, a window is opened with window.open(); syntax. What I need seems to be simple: when the window is closed, return to the window that opened the popup a response from the server, that can be true or false — like the Facebook's API does.
Someone knows how can I do this in a simple way?
Spotlight
I don't want to use jQuery because the page's CSS is overwriting the popup's CSS.
Current syntax
HTML:
[...]
<a href="#" class="share" data-networkName="<?php echo $network->name; ?>">
Share</a>
[...]
JS:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.open("share.php?network=" + networkName");
});
This is what I came up with:
UPDATE
receive.html
Share
<script>
var new_window = null;
function openWindow() {
new_window = window.open('return.html');
}
// Callback Function that we will call in child window
function sendMessage(message) {
alert(message);
new_window.close();
}
</script>
return.html
Mark As Shared
<script>
function messageParent() {
// Calls sendMessage function on the parent window.
window.opener.sendMessage("Hello World!");
}
</script>
You could then handle the return value that you would like to in the sendMessage function in the parent window.
This is the simplest method I could come up with. Please let me know if this works.
Try this:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.onbeforeunload = function() {
window.open("share.php?network=" + networkName");
}
});
UPDATE
main.php's script:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.onbeforeunload = function() {
window.open("share.php?network=" + networkName");
}
function send(msg) {
//send msg to db or store as cookies
}
});
popup.html's script: [Let's say you have a share button called '#popup-btn']
$('#popup-btn').click(function() {
window.opener.send('MSG SENT FROM POPUP {THEY SHARED SOMETHING}');
});