Slidetoggle to retain current state when page is refreshed - javascript

I have this code, which works but goes back to initial closed state whenever I reload or refresh page. I want retain last toggle state even after page reload. Can't seem to get my head around this problem.
My code is:
var $answers = $('.contentbar');
$(".titlebar").click(function () {
var $ans = $(this).next(".contentbar").stop(true).slideToggle(500);
$answers.not($ans).filter(':visible').stop(true).slideUp();
})

There's a plugin called jQuery.cookie. Using that you can check if there's already a user-set accordion and based on the preference, you can show / hide stuff by default.
var $answers = $('.contentbar');
$(".titlebar").click(function () {
if (!$.cookie('contentbar'))
var $ans = $(this).next(".contentbar").stop(true).slideToggle(500);
else
{
var $ans = $($.cookie('contentbar')).next(".contentbar").stop(true).slideToggle(500);
$.cookie('contentbar', this);
}
$answers.not($ans).filter(':visible').stop(true).slideUp();
});

Related

Live Chat reload object to set new group

And Thanks in Advance :)
So I am using Live Chat and want to dynamically change the group based on a user action.
IF user has a chat open THEN keep current chat open (this part is fine)
If user clicks link A then they will get assigned to groups 1-5 depending on another variable
If user clicks link B then they will get assigned to group 6
Now I can get all of the above IFs to work independently....but when I try to change the group ID dynamically it doesnt take... I've tried resetting the object then reloading the library again to no avail :(
// Inside $(document).ready()
window.__lc = window.__lc || {};
window.__lc.license = LICENSE_ID;
window.__lc.group = live_chat_group;
window.__lc.chat_between_groups = false;
window.LC_API = window.LC_API || {};
window.LC_API.on_before_load = function() {
if (window.LC_API.visitor_engaged() === false && livechat_chat_started === false) {
window.LC_API.hide_chat_window();
}
};
window.LC_API.on_chat_started = function() {
livechat_chat_started = true;
};
$.getScript('https://cdn.livechatinc.com/tracking.js', function() {});
So the above gets loaded on page load to keep the current chat session between pages
$("body").on("click", "#sales-chat-init", function () {
window.__lc = {};
window.LC_API = {};
window.__lc.license = LICENSE_ID;
window.__lc.group = 2;
window.__lc.hostname = "";
window.__lc.chat_between_groups = false;
$.getScript('https://cdn.livechatinc.com/tracking.js?q=52895293523', function() {});
console.log(window.__lc);
//window.LC_API.open_chat_window();
});
The above doesnt work...window.__lc is just the object I created and not tied re-init'd as the LiveChat object.
I work at LiveChat so let me help you with that :)
There is no option to change a group in the chat window if the LiveChat script is already loaded. However there are two ways you can handle it:
A) ask your users to pick a group in a pre-chat survey
B) create kind of 'pre-chat' on your site and load the script after the group will be chosen (this is available only once per session), here's an example http://lp.labs.livechatinc.com/helpers/group_chooser/
Perhaps the user needs to leave the chat first
LC_API.close_chat();
then start again...
https://developers.livechatinc.com/javascript-api/#close-chat

Retaining scrollbar position using jquery

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();
...
}

auto reload div with toggle checkbox and user selected interval

I have a chart that is dynamically created every time my page loads. I have it in a <div id="plot"></div> block. I would like to give the user the ability to toggle auto refresh on/off AND select the refresh rate. There are lots closely related solutions to this, but none that combines this and I'm struggling. For toggling a full reload, I'm using this example. This works well. However I can't figure out how to extend it to let the user select a interval from something like: <select name="interval" id="interval">
<option value="1000">1</option>
<option value="2000">2</option>
<option value="5000">5</option>
<option value="10000">10</option>
</select>
I seem to both not know how to pass that result into the javascript and make it remember the interval after the reload. I'm guessing I need to not only pass it into the javascript, but somehow cancel the current timeout and reset it to the new value?
Maybe do something simple like pass in a second parameter of the interval select id in the onClick event like:
<input type="checkbox" onclick="toggleAutoRefresh(this, 'interval');" id="reloadCB"> Auto Refresh
Then in the JS set a new variable with the interval selection and if the page reloads include the interval time after #autoreload and pass it between reloads in the anchor hash:
var reloading;
$(document).ready(function () {
$('#interval').change(function () {
if (document.getElementById("reloadCB").checked) {
var intervalSelection = $(this).find(":selected").val();
window.location.replace("#autoreload-" + intervalSelection);
reloading = setTimeout("window.location.reload();", intervalSelection);
} else {
window.location.replace("#");
clearTimeout(reloading);
}
});
});
function checkReloading() {
if (window.location.hash.substring(0, 11) == "#autoreload") {
var intervalSelection = window.location.hash.substring(12, window.location.hash.length);
reloading = setTimeout("window.location.reload();", intervalSelection);
document.getElementById("reloadCB").checked = true;
var intervalSelect = document.getElementById('interval');
var intervalOptions = intervalSelect.options.length;
for (var i = 0; i < intervalOptions; i++) {
if (intervalSelect.options[i].value == intervalSelection) {
intervalSelect.options[i].selected = true;
break;
}
}
}
}
function toggleAutoRefresh(cb, intervalID) {
var intervalSelection = $('#' + intervalID).find(":selected").val();
if (cb.checked) {
window.location.replace("#autoreload-" + intervalSelection);
reloading = setTimeout("window.location.reload();", intervalSelection);
} else {
window.location.replace("#");
clearTimeout(reloading);
}
}
window.onload = checkReloading;
Haven't tested any of this and probably not the most elegant solution but first thing that came to mind.
Edit: Added some code to set drop down to value passed through hash tag as well as some JQuery to detect change of value on drop down and set new interval time.

display message javascript while a calculation is being made

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.

How do i call a spcific jquery function form within another function?

I have the following code which is not working
jQuery
jQuery(window).bind("load", function() {
function effects(content_name,active_name)
{
// switch all tabs off
$(active_name).removeClass("active");
// switch this tab on
$(this).addClass("active");
// slide all content up
$(content_name).slideUp();
// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();
}
$("a.tab_1").click(function () {
var content_name = '.content_a';
var active_name = 'a.tab_1.active';
effects(content_name,active_name);
});
$("a.tab_2").click(function () {
var content_name = '.content_b';
var active_name = 'a.tab_2.active';
effects(content_name,active_name);
});
$("a.tab_3").click(function () {
var content_name = '.content_c';
var active_name = 'a.tab_3.active';
effects(content_name,active_name);//create effects with the content
});
});
Its a set of tab groups upto 8 in number. Writing individual functions will have an adverse effect on loading time.
Answer 2 hours later:
Thank you all for pointing out the "effetcs" mistake in the code.
The other mistake was I was doing was not passing "$(this)" as a parameter into the called function "effects".
I Have adjoined the link where the necessary changes are done and the code works.
[jsfiddle] http://jsfiddle.net/phyGS/2/
Replace effetcs with effects at the first block, and replace every occurrence of
effects(content_name,active_name);
with
effects.call(this, content_name, active_name);
This call method assigns a new value to the this property of function effects.

Categories