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();
Related
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.
I have a java function,
private GroupsSelector group(LabourInputReportCriteria.Level level) {
HtmlSelectBooleanCheckbox box = new HtmlSelectBooleanCheckbox();
boolean isSelected = selections.isGroupSelected(level);
box.setSelected(isSelected);
// box.setDisabled(isDaySelectedOnFirst(level));
String id="groupBy" + level.getClass().getSimpleName();
box.setId(id);
box.setOnclick("submit()");
box.addValueChangeListener(u.addExpressionValueChangeListener("#{reportSearchCriteriaModel.groupBy}"));
HtmlOutputText labelComponent = new HtmlOutputText();
labelComponent.setValue(getGroupSelectionValue(level));
tr().td();
html(box);
html(" ");
html(labelComponent);
//html("<span id='"+id+ "'></span>");
//html("<script> function resetGroupsSelector() { var x = document.getElementById('search_report_form:groupByWeekLevel'); alert(x); } </script>");
endTd().endTr();
return this;
}
Whenever I click on a checkbox, sumbit() is called and it has some functionality at the backend. Now, my question is whenever I click on a checkbox, the scrollbar position is moving up i.e, it is going on top of the page. I want to avoid this. I want to retain my scrollbar position as it is. How am I supposed to do it?
I tried adding the follwing code but it dint work.
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" >
var addTweet = function() {
var scrollPosition = $(document).scrollTop();
$('#results9016').prepend($newTweet);
$('html, body').scrollTop(scrollPosition);
}
</script>
Please help.
inside the function that you call when clicking you can say
function submit(event) {
event.preventDefault();
...
}
I have a html webpage. It contains a very long text passage.
User can use internet browser to read the passage. Since the passage is long, users need to scroll the page to read the whole passage.
I would like to add a floating box button for user to click. After clicking the button, I can capture the current viewing portion of the passage.
So that users can log in later and continue reading.
I think I need to add some javascript, but after hours of online searching, I failed to find relevant information.
Please kindly suggest the possible solution to do so?
Use a position:fixed box/button. Clicking it stores (or updates, if it already exists) a localStorage item or cookie with the current position. On page load, if that item exists, ask the user if they want to return to that spot.
There are two ways of doing this:
Save position as a pixel value. This works perfectly if the user's display will not change size (switching computers, switching monitors, changing screen resolution setting, etc.). However, if any of those changes do occur, the absolute pixel value of the saved position is not consistent with the position on the page.
Demo. To run: click "Save position", scroll anywhere, then reload the page.
Save position as a percentage of total height. This works exactly as solution (1), but handles all cases in which screen size changes as well. (Use this one.) The code provided below pertains to this solution.
Demo. To run: click "Save position"; change the width of the "Result" quadrant; without changing any code, click "Run" again.
The saved item is removed regardless of the user's choice (to return to the last spot or not), so that the prompt doesn't show up every time the page is reloaded (which can get annoying).
This is pure JS; it's very modular; it demonstrates simple usage of localStorage and falls back gracefully to cookies.
HTML
<div id="save">
<button id="saveButton">Save position</button>
<span id="saved">Saved!</span>
</div>
<div id="content">
<!-- Disgustingly long content -->
</div>
CSS
#save {
position:fixed;
top:30px;
left:10px;
width:20%;
}
#saved {
visibility:hidden;
color:green;
}
#content {
width:60%;
margin:auto;
}
JS
function checkStorageSupport() {
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
function getTotalHeight() {
return document.body.clientHeight;
}
function getSavedPercent() {
var percent = storageSupported ? loadFromStorage() : loadFromCookie();
return (percent == null || percent == "") ? 0 : percent;
}
/******* Save *******/
function saveInStorage() {
localStorage.setItem("scrollPercent", (document.documentElement.scrollTop / getTotalHeight()));
}
function saveCookie() {
var expDate = new Date();
expDate.setDate(expDate.getDate() + 7); // start over if it's been more than ___ days
document.cookie = "scrollPercent=" + (document.documentElement.scrollTop / getTotalHeight())
+ "; " + expDate;
}
/******* Load *******/
function loadFromStorage() {
return localStorage.getItem("scrollPercent");
}
function loadFromCookie() {
return document.cookie.replace(/(?:(?:^|.*;\s*)scrollPercent\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}
/******* Remove *******/
function removeFromStorage() {
localStorage.removeItem("scrollPercent");
}
function removeCookie() {
document.cookie = "scrollPercent=''";
}
/******* Handler *******/
var saveButton = document.getElementById("saveButton"),
saved = document.getElementById("saved");
saveButton.onclick = function() {
storageSupported ? saveInStorage() : saveCookie();
saved.style.visibility = "visible";
setTimeout(function() {
saved.style.visibility = "hidden";
}, 1500);
};
/******* Logic *******/
var storageSupported = checkStorageSupport(),
percent = getSavedPercent();
if (percent > 0) {
if (confirm("Would you like to continue reading where you left off?")) {
document.documentElement.scrollTop = percent * getTotalHeight();
}
storageSupported ? removeFromStorage() : removeCookie();
}
Note: to get back to the code that produces solution (1), copy the code from that demo. In the case JSFiddle goes down, here are manual instructions:
Remove every instance of / getTotalHeight() in a "Save" function
In the "Logic" section, replace position * getTotalHeight() with position
Remove getTotalHeight(), since it's not used
Replace instances of "percent" with "position" to be more semantically accurate
Basic idea is..
create a floating bookmark button on the page like:
#mybookmark{
position: fixed;
top:30px;
right:0;
}
Now in jquery.. retrieve the position of this floating bookmark when clicked on it..
$('#mybookmark').click(function(){
var bookmark_loc = $('#mybookmark').offset().top();
});
Store this bookmark_loc data in your preferred storage for the user.
then when they clicks on a button, you can scroll to the stored offset value in your storage.. in jquery
$('#scroll_to_bookmark').click(function{
var bookmark_loc = //Fetch bookmark
$('body').animate({ scrollTop: bookmark_loc; });
});
Currently I hide and show the content of a div like this:
var header = null;
var content = null;
var mainHolder = null;
var expandCollapseBtn = null;
var heightValue = 0;
header = document.getElementById("header");
content = document.getElementById("content");
mainHolder = document.getElementById("mainHolder");
expandCollapseBtn = header.getElementsByTagName('img')[0];
heightValue = mainHolder.offsetHeight;
header.addEventListener('click', handleClick, false);
mainHolder.addEventListener('webkitTransitionEnd',transitionEndHandler,false);
function handleClick() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
mainHolder.style.height = "26px";
content.style.display = "none";
}
else
{
mainHolder.style.height = heightValue + "px";
}
}
function transitionEndHandler() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
expandCollapseBtn.src = "expand1.png";
}
else{
expandCollapseBtn.src = "collapse1.png";
content.style.display = "block";
}
}
This is fine if the content is static, but I'm trying to populate my div dynamically like so.
This is called from an iphone application and populates the div with a string.
var method;
function myFunc(str)
{
method = str;
alert(method);
document.getElementById('method').innerHTML = method;
}
I store the string globally in the variable method. The problem I am having is now when I try expand the div I have just collapsed there is nothing there. Is there some way that I could use the information stored in var to repopulate the div before expanding it again? I've tried inserting it like I do in the function but it doesn't work.
Does anyone have any ideas?
to replicate:
Here is the jsfiddle. jsfiddle.net/6a9B3 If you type in text between
here it will work fine. I'm not sure
how I can call myfunc with a string only once in this jsfiddle, but if
you can work out how to do that you will see it loads ok the first
time, but when you collapse the section and attempt to re open it, it
wont work.
If the only way to fix this is using jquery I dont mind going down that route.
is it working in other browsers?
can you jsfiddle.net for present functionality because it is hard to understand context of problem in such code-shoot...
there are tonns of suggestions :) but I have strong feeling that
document.getElementById('method')
returns wrong element or this element not placed inside mainHolder
update: after review sample in jsfiddle
feeling about wrong element was correct :) change 'method' to 'info'
document.getElementById('method') -> document.getElementById('info')
I think you want to use document.getElementById('content') instead of document.getElementById('method') in myFunc.
I really see nothing wrong with this code. However, a guess you could explore is altering the line
content.style.display = "none";
It might be the case that whatever is displaying your html ( a webview or the browser itself) might be wiping the content of the elemtns, as the display is set to none
I created a simple RSS web app using the template in Dashcode. Problem is, when choosing items in the list from the feed the transition flickers (even with the default settings). I am guessing its because of the images in the posts.
I tried disabling the transitions completely but even then I get a flickering when returning to the list. This problem does not appear to affect safari on OSX only on the iphone.
Here is the code that I think is responsible:
var topStories = parseInt(attributes.topStories, 30);
function load()
{
dashcode.setupParts();
// set today's date
var todaysDate = document.getElementById("todaysDate");
todaysDate.innerText = createDateStr(new Date()).toUpperCase();
setupFilters("headlineList");
// This message checks for common errors with the RSS feed or setup.
// The handler will hide the split view and display the error message.
handleCommonErrors(attributes.dataSource,
function(errorMessage) {
var stackLayout = document.getElementById("StackLayout")
if (stackLayout) {
stackLayout.style.display = 'none';
}
showError(errorMessage);
});
// get notifications from the stack layout when the transition ends
document.getElementById("StackLayout").object.endTransitionCallback = function(stackLayout, oldView, newView) {
// clear selection of lists when navigating to the first view
var firstView = stackLayout.getAllViews()[0];
if (newView == firstView) {
document.getElementById("headlineList").object.clearSelection(true);
}
}
}
function articleClicked(event)
{
document.getElementById("StackLayout").object.setCurrentView("articlePage", false, true);
}
function backToArticlesClicked(event)
{
document.getElementById("StackLayout").object.setCurrentView("frontPage", true);
}
function readMoreClicked(event)
{
var headlineList = dashcode.getDataSource('headlineList');
var secondHeadlines = dashcode.getDataSource("secondHeadlines");
var selectedItem = null;
if (headlineList.hasSelection()) {
selectedItem = headlineList.selectedObjects()[0];
} else if (secondHeadlines.hasSelection()) {
selectedItem = secondHeadlines.selectedObjects()[0];
}
if (selectedItem) {
var link = selectedItem.valueForKeyPath('link');
// If the link is an object, not a string, then this may be an ATOM feed, grab the actual
// href from the href attr
if (typeof(link) == 'object') {
link = selectedItem.valueForKeyPath('link.$href');
// If the link is an array (there is more then one link), just grab the first one
if (DC.typeOf(link) == 'array') {
link = link[0];
}
}
window.location = link;
}
}
var headlineListDataSource = {
// The List calls this method once for every row.
prepareRow: function(rowElement, rowIndex, templateElements) {
if (rowIndex >= topStories) {
templateElements['headlineDescription'].style.display = 'none';
templateElements['headlineTitle'].style.fontSize = '15px';
}
}
};
The following CSS rule fixed all of my "-webkit-transition" animation flickering issues on the iPad:
body {-webkit-transform:translate3d(0,0,0);}
I am not sure how well that applies to your problem but in general you should set the backface visibility to hidden if not needed. That will most likely kill all flickering on a page.
-webkit-backface-visibility: hidden;