I'm using cookies to scroll to different sections of a given page. The cookies are saved fine. Only one cookie can exist at a given time. I can see them in the application as they should be. However, there is an issue with my conditionals where only the last if statement runs.
jQuery(document).ready(function ($) {
var internetcsomagcookie = null;
var csomagcookie = "true";
var triocsomagcookie = null;
var tvcsomagcookie = null;
if ((csomagcookie = "true")) {
document.getElementById("csomag").scrollIntoView();
}
if ((triocsomagcookie = "true")) {
document.getElementById("trio").scrollIntoView();
}
if ((internetcsomagcookie = "true")) { document.getElementById("internet").scrollIntoView();
}
if ((tvcsomagcookie = "true")) {
document.getElementById("tv").scrollIntoView();
}
});
#internet,#trio,#tv,#csomag {height:1000px;}
#internet {background:blue;}
#tv {background:red;}
#csomag {background:green;}
#trio {background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="csomag"></div>
<div id="trio"></div>
<div id="internet"></div>
<div id="tv"></div>
The issue is, that after creating any of the cookies (except for the last one - tvcsomagcookie), whenever I load the page where I want the scrolltoview to happen on, it jumps to the last ID in the code (basically the last if statement executes that scrolls to #tv), despite the tvcsomagcookie returning 'null'. So it runs when it should not.
If statements were originally posted with = (which is for assignment) instead of == for comparison. Updating this inside the code fixed the issue.
Related
Context: I am trying to hack together a script that detects a session variable and hides a UI element when the variable !== null.
This is the script:
var userid = $('#userid').attr('data-id');
var signUpContainer = $('#sign-up-container');
if (userid != null) {
$('#sign-up-container').css('display','none');
};
This script works perfectly fine. However, when I use the variable instead:
if (userid != null) {
signUpContainer.css('display','none');
};
nothing happens. Any reasons why this is the case?
Note: I've never run into this issue before while storing a jquery object in a variable, and it seems to only occur when trying to change CSS.
This problem must be somewhere else in your code.
You should be able to store references to jQuery objects in variables without any issues. See the following example which works perfectly fine:
var userid = $('#userid').attr('data-id');
var signUpContainer = $('#sign-up-container');
if (userid != null) {
signUpContainer.css('display','none');
};
#sign-up-container {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='userid' data-id='test'></div>
<div id='sign-up-container'>Signup Container</div>
I'm using several functions in the $(document).ready(function(){ part of the page.
The old functions (highlighted below) worked fine until I added the new one (added at the top). Since then they do not work anymore.
After some testing I realized that if I switched position between the old and the new functions, only the one placed at the top will work.
I'm using the new function on a different page than the old ones but both are included in my javascript file and in the footer.
home.js :
$(document).ready(function(){
// NEW FUNCTION (up/down arrows)
var nextListitem;
var noOfListItems = $("#select > option").length-1;
var curListItem = $("#select")[0].selectedIndex;
$("#upArrow").on("click", function(){
// Decrement the selection by one, unless that will be less than zero, then go to the last option
nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1;
curListItem = nextListitem;
$("#select")[0].selectedIndex = nextListitem;
});
// OLD FUNCTIONS (count characters left in textarea)
window.com_domain = window.com_domain || {};
$(':text,#resort_description').click(function(){
current_input_val = $(this).val();
$(this).select();
}).focusout(function(){
if ($(this).val() == '') {
$(this).val(current_input_val);
}
});
// more old functions
});
TypeError: $(...)[0] is undefined
var curListItem = $("#select")[0].selectedIndex;
Is displayed if I load the page using the "old functions".
This is how my footer looks like (Jquery is called before) :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="js/bootstrap-hover-dropdown.min.js'>"></script>
<script src="js/home.js" type="text/javascript"></script>
If there's no element with id="select" on the page, $("#select") will be an empty collection, so $("#select")[0] will be undefined. You can't access undefined.selectedIndex, so you get an error at that line and nothing after it runs. It has nothing to do with having multiple functions in the ready block.
You should check whether the element exists first.
if ($("#select").length > 0) {
var nextListitem;
var noOfListItems = $("#select > option").length-1;
var curListItem = $("#select")[0].selectedIndex;
$("#upArrow").on("click", function(){
// Decrement the selection by one, unless that will be less than zero, then go to the last option
nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1;
curListItem = nextListitem;
$("#select")[0].selectedIndex = nextListitem;
});
}
First of all I think that you have a mistke on your import of the the bootstarp minified js file
script src="js/bootstrap-hover-dropdown.min.js"></script>
Basically I have this header that slides out of the way when people don't want it anymore and can be slid down again when they want it. I want it to be down by default however I don't want people to have to constantly click the header toggle every-time a new page loads. I have read about using cookies but my skill in javascript is rather limited. Here is the code I currently use that works well:
<div id="headtoggle" onclick="headertoggle()"></div>
<script>
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
top = "-11px";
pagetop = "275px";
} else {
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
How do I change the code so that it "remembers" what the last setting was for each person? I am willing to also use jquery. Any help for this very novice coder would be more than appreciated.
Thanks,
Dylan
EDIT2: I changed the code given to me a bit and am having a new problem.
<div id="headtoggle" onclick="headertoggle()" onload="topposition()"></div>
<script>
function topposition() {
var top;
var pagetop;
if (localStorage.getItem("headerDown") == "false") {
top = "-11px";
pagetop = "275px";
} else {
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
<script>
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
localStorage.setItem("headerDown", false);
top = "-11px";
pagetop = "275px";
} else {
localStorage.setItem("headerDown", true);
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
The toggle works as intended however whenever I fire "function topposition ()" in the firefox console I get the following error:
SyntaxError: expected expression, got end of script data:,/*
EXPRESSION EVALUATED USING THE FIREBUG COMMAND LINE:
*/%0A%09function%20topposition() Line 2
You can create a cookie by using
document.cookie="headerDown=true";
Then when the header is moved up overwrite the cookie with the same code changed to false.
If you then add some code that reads the cookies on page load you will be able to determine what is need.
You can read cookies by accessing document.cookie which will be a string of any cookies available in the following format.
cookie1=value; cookie2=value; cookie3=value;
Look for your cookie and you should be able to set whether the header is up or down from there.
i would say local storage would be a good option for this. Just log an event or variable or whatever and then check for it each time you load the page.
https://developer.mozilla.org/en-US/docs/Web/API/Window.localStorage
Using local storage will allow you to save variables between page loads.
add localStorage.setItem(name,value) in to your if statements as below.
If you are only using the headerToggle function to position these elements then the if statement below the function should suffice. It requires two calls to the headertoggle function in the even that you want the header to be down.
You will need to make sure the if statement is placed after the html for the divs, most likely best place is the very bottom of the page.
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
localStorage.setItem("headerDown", true);
top = "-11px";
pagetop = "275px";
} else {
localStorage.setItem("headerDown", false);
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
if (localStorage.getItem("headerDown") == "true") {
headertoggle();
}
headertoggle();
I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.
I'm trying to access control's properties and although it works great in IE6, in FF3, it fails. I'm doing:
alert(document.getElementById(gridViewCtlId).style.display);
alert(document.getElementById(gridViewCtlId).style);
And the first one shows a blank popup while the second shows 'undefined'.
I do
alert(document.getElementById(gridViewCtlId).id);
and I get the proper ID of the box along with:
alert(document.getElementById(gridViewCtlId));
and I get that in an HTML table.
This works perfectly in IE but not FF. What do I need to do to get this functioning?
Edit: gridViewCtlId is defined as:
var gridViewCtlId = '<%=GridView.ClientID%>';
Here is the full code:
var itemVisible= '<%=ItemVisible.ClientID%>';
function onGridViewRowSelected(rowIdx)
{
alert(document.getElementById(gridViewCtlId).style.display);
alert(document.getElementById(gridViewCtlId).style);
if (document.getElementById(gridViewCtlId).disabled == false)
{
alert("hi1");
var selRowCCA = getSelectedRow(rowIdx);
if (curSelRow != null)
{
alert("hi2");
var previousRow = getSelectedRow(previousRowIndx);
var CountIdx = previousRowIndx % 2;
if (document.getElementById(itemVisible) == null)
{
if (CountIdx == 0)
{
alert("hi");
previousRow.style.backgroundColor = 'Silver';
}
else
{
previousRow.style.backgroundColor = 'White';
}
}
}
if (null != selRow)
{
alert("new");
previousRowIndx = rowIdx;
curSelRow = selRow;
selRow.style.backgroundColor = 'Red';
}
}
}
It's pretty much an onClick where I have to call that function to turn it back to its original color (using alternating color rows). IE, this works fine. If i do the first alert
alert(document.getElementById(gridViewCtlId).disabled);
I would get either true or false.
The reason it's like this is because someone is going to enter something in a text box and the first gridview is going to populate depending on whats in that textbox. Then when someone selected something in the first gridview, that gridview is going to become disabled and then populate a second. So i'm having an issue checking for the disabled part of the gridview.
<div id="test">
</div>
<script type="text/javascript">
var gridViewCtlIdCCA = 'test';
alert(document.getElementById(gridViewCtlIdCCA).style);
</script>
Alerts [object CSSStyleDefintion] in Firefox 2 and 3.
If .style where undefined, .style.display would produce an error, not alert an empty dialog (unless you are capturing window.onerror).
Can you create an SSCCE that demonstrates the problem. More information about SSCCE available here.