function display() {
document.querySelector(".recipeList").innerHTML = "";
for (var i = 0; i < arrayOfRecipes.length; i++)
+document.querySelector(".recipeList").innerHTML += "<button onclick='buttonDirect(" + i + ")'>Start Cooking</button>";
}
function buttonDirect(indexNum) {
localStorage.setItem("indexNumber", JSON.stringify(indexNum));
window.location.href = "/display.html";
buttonClicked();
}
function buttonClicked() {
JSON.parse(localStorage.getItem("indexNumber"));
console.log(indexNumber);
}
I am trying to get data (index number) from one function to carry on running after the HTML page has been changed.
Currently, I have a button which runs a function called "buttonDirect(indexNum)" I want this function to change from one page to another, hence why I used the window.location.href = "/display.html"; code within the function. After this, the page changes so I attempt to save the index number by saving it to local storage with the localStorage.setItem("indexNumber", JSON.stringify(indexNum)); code. Then since JavaScript reads the code from top to bottom, I tried to make it run the buttonClicked(); function after the page has changed so that it doesn't run until the next page has loaded. That way, I can retrieve the index number on the next page using JSON.parse(localStorage.getItem("indexNumber")); and then console log that number with console.log(indexNumber);.
I quickly realised that this will not work, because the buttonClicked() function will run before the page actually changes, meaning that the indexNumber will not get logged once the page changes. What is the best way to achieve what I am trying to do?
It looks like buttonClicked() won't get called because you would have left the page.
You can, when the page loads, get the data you want from local storage:
window.onload = function() {
const indexNumber = JSON.parse(localStorage.getItem("indexNumber"));
console.log(indexNumber);
}
(I added a variable for the result of JSON.parse.)
By the way, on the fourth line, I don't know if the + there is a typo
+document.querySelector...
^
Related
For class, I'm trying to build a single page web page using jquery. One of the components of this is changing the HTML to find the correct ID to show the proper information needed.
I'm running into an issue where after the HTML is changed, the HTML is reverted to its original text. I've done some googling and I learned that it's reverting because of the page switch. Most of the questions already asked about this are dealing with form submissions so I'm not really sure how to deal with it in my case.
What I've tried already is having a global variable that keeps track of the ID but when I switch pages, the global variable also gets reset to its original value. I know that the value is getting reset because I have a console log of before and after.
function createList() {
let liArray = Array.from(document.getElementsByClassName("oneMusic"));
liArray.forEach(function (element) {
element.addEventListener("click", function () {
var parm = this.getAttribute("data-parm"); // passing in the record.Id
document.getElementById("IDparmHere").textContent = parm;
console.log(
"parm: " + document.getElementById("IDparmHere").innerHTML
);
param = parseInt(parm);
console.log("param" + param);
// now jump to our page that will use that one item
setTimeout(() => {
document.location.href = "index.html#details";
}, 1000);
});
});
}
And then the code that handles transferring pages. To note, param is the global var.
document.addEventListener("DOMContentLoaded", function (e) {
createList();
$(document).on("pagebeforeshow", "#details", function (event) {
console.log("param 2: " + param);
let localID = param;
let idx = GetArrayPointer(localID);
console.log("local id: " + localID);
console.log("arrayPointer: " + arrayPointer);
document.getElementById("oneTitle").innerHTML =
"The title is: " + songArray[idx].Song;
});
});
So the createList() does a bunch of things but at the end of it, it adds an event listener to each of the li elements. When you click on it, you pull the specific ID of that li and then you get transferred to the details page.
By the time the code reaches the details page, both the HTML and the global var revert back to their original values, which makes it useless in figuring out the ID.
For example, if #IDparmHere was changed from "blank" to "1", then after the page switch happens, #IDparmHere is changed back to "blank".
I set the global var as null initially, after it's changed from null to 1 or 2 or 3, after the page switch it goes back to null.
Also, parm is supposed to be "param" but the instructor that gave us the skeleton of this code has dyslexia so..
I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};
I have a date input in my page, which I'm using Daterangepicker framework to populate it.
Here is the code of how I start my page!
$(function(){
startSelectors();
var variaveis = returnInputVars();
var rede = variaveis[0];
var codLoja = variaveis[1];
var period = variaveis[2];
console.log('1.'+rede+' 2.'+codLoja+' 3.'+period);
});
function returnInputVars(){
var rede = $("#dropdown-parceria").val();
var codLoja = $("#dropdown-loja").val();
var periodo = $("#datepicker-range").val();
return [rede, codLoja, periodo];
};
The function startSelectors() is set to start my datepicker and other fields, which is working perfectly. After it, I create a var called "variaveis" to fill
with the values of each field because I will use then later (this functions also works perfectly at other scripts of my page).
Running the page, my console returns this:
The funny thing is, if I type at the console this, the value is shown, just while starting the script is does not work!
Anybody experienced something like this?
***UPDATE
Adding this script to my start function:
console.log($("#datepicker-range"));
The value is shown, but the second console.log don't:
EDIT 1. FIDDLE (Suggested by #halleron)
To ensure things are loaded in the correct order, it is useful to apply a page sniffer code snippet that will scan the page continuously until a condition is met, or until a preset counter limit is reached (to prevent strain on browser memory). Below is an example of what I typically use that would fit your scenario.
I think because you are dealing with asynchronous loading, you can't have a global variable that holds the values in a global scope without an interval to detect when it can be used. Otherwise, it will attempt to read the variable when it is not yet ready.
You can invoke functions anywhere you like. But I would keep all of your variables contained within the page_sniffer_2017() because that is a controlled environment where you know that everything successfully loaded and you know that the variables are ready to be accessed without error.
That way, regardless of connection speed, your functions will only fire when ready and your code will flow, sequentially, in the right order.
Within the ajax success options, always add a class to the body of the document that you can search on to determine if it has finished loading.
$(document).ready(function() {
page_sniffer_2017();
});
function page_sniffer_2017() {
var counter = 0;
var imgScanner = setInterval(function() {
if ($("#datepicker-range").length > 0 && $("#datepicker-range").val().length && jQuery('body').hasClass('date-picker-successfully-generated')) {
var periodoDatepicker = $("#datepicker-range").val(); // ok
console.log(periodoDatepicker); // ok
var variaveis = returnInputVars(replaceDate(periodoDatepicker)); // ok
console.log(variaveis[0], variaveis[1], variaveis[2]);
//startNewSelectors(variaveis);
// start ajax call
generateData(variaveis[0], variaveis[1], variaveis[2]);
clearInterval(imgScanner);
} else {
//var doNothing = "";
counter++;
if (counter === 100) {
console.log(counter);
clearInterval(imgScanner);
}
}
}, 50);
}
i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}
Is there a way using the code below to instead of refreshing the time refresh a div id that is already there?
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('drawaddrow').innerHTML = ????;
}
</script>
Say I fi were to replace the time id with the the id that I wanted to refresh what would I put after .innerHTML =???
This is the div I need refreshed every second.
<div id="draw" align="center">
<table>
<tr><td style="height:20px;"></td></tr>
</table>
<TABLE style="float:center;border:5px; border-style:outset;border-color:#E80000; width:850px; border-spacing:0; border-collapes:collapse;" table border="1">
<div id="addrow"><script type="text/javascript">
Draw ("")
[Add]</script></div>
</table>
</div>
The [AddItemsHTML] somehow pulls data from a piece of software telling you what is due and what is not, however the script is not pulling the time every second the browser when refreshed just changed the time on the due status column.
Right now i'm using this to refresh the whole page I just need the drawaddrow div id refreshed.
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 1000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
Updated (on 27/07/2013 #08:20 AM IST):
Having gone through your code, the below is my updated answer.
Plainly assigning a value to the DIV (divaddrow) using (.innerHTML) wouldn't work due to the following reasons:
(a) The DIV has some code enclosed within square braces (like [AddItemsHTML]). I am not sure what technology it uses. But judging by its intended use (which is, to populate the table with data) it sure seems to require a communication with the server to fetch data.
(b) The DIV also has a <script> tag with a call to a function (lets call it cntFn). Plainly assigning the value would not work because value setting wouldn't call/execute the function again (like it does on page load).
Assuming point 1.a is wrong, the normal way to handle 1.b would be to first assign the static contents of the div using .innerHTML and then do either (a) write whatever the "cntFn" does into the function that is refreshing the page (lets call it refreshFn) also (or) (b) call the "cntFn" within the "refreshFn". The latter would also cause a problem here because the "cntFn" has a lot of document.write lines which would repaint the entire page (meaning the other contents of the page would be lost on executing the refresh).
Generally using document.write lines is a bad practice because they repaint the page fully. You can find more about this here.
The best alternate in my opinion would be to use AJAX to refresh the contents. The content of your divaddrow div would form the contents of the AJAX file that needs to be called every 'x' seconds. Be careful with the 'x' seconds part. Do not try to refresh the section every second because realistically it would take time for the AJAX request to reach the server and get the response. Set the refresh interval such that the first request would have been processed by the time the next one comes (at-least 90% of the cases). The amount of data (no. of rows) that the AJAX call would be fetching will also be a factor.
Check this out... I used Jquery for the same
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 3000);
});
WORKING FIDDLE
I'm not sure that I understand you, but is this want you mean?
function startTime()
{
document.getElementById('time').innerHTML = document.getElementById('target').innerHTML;
}
This is what I use:
<span>This page will refresh in </span><span id="countdown">60</span>seconds…
<script type="text/javascript">
setInterval(
function() {
if (document.getElementById('countdown').innerHTML != 0) {
document.getElementById('countdown').innerHTML--;
} else {
window.location = window.location;
}
}, 1000);</script>
If I've understood your question correctly, you can do something like this:
window.onload = function () {
function startTime () {
document.getElementById('date').innerHTML = new Date();
}
setInterval(startTime, 1000);
}
HTML:
<div id="time">This a div containing time: <span id="date"></span></div>
This is a JavaScript snippet, based on the original post, that counts the number of seconds since the page has loaded, assuming that there's an element with ID "time" and contents that are entirely numeric.
If the time remaining is given in seconds on the page you're working with, then it would be easy to adjust this accordingly. If the time remaining is not given in seconds, I'd need to see what the text in question actually looks like.
window.onload = startInterval;
var firstTime;
var valAtPageLoad;
function startInterval()
{
firstTime = new Date();
valAtPageLoad = parseInt(document.getElementById('time').innerHTML);
setInterval("startTime();",1000);
}
function startTime()
{
var timeDiff = (new Date() - firstTime)/1000;
document.getElementById('time').innerHTML = Math.round(timeDiff + valAtPageLoad);
}
If you want to reload your DIV and not the entire page, you would have to create the contents of that DIV on the server-side, and then use AJAX to load the DIV´s content. The easiest way to do this, is with jQuery:
function startTime() {
$.get('path/to/div/contents.html', function(data) {
$('#drawaddrow').html(data);
});
}