set cookie for toggle menu - javascript

I'm trying to set a cookie depending on every click on button. I have a button with toggle rule . When user choose open menu-toggle , it should be save cookie for about a week ... The next time (second click ot button - toggle menu is hide) it must change cookie value ...
when cookie value is 1 - menu must be open always, and when value is 2 - menu must be close always ..
button:
<ul class="nav navbar-nav navbar-right">
<li>
<div class="navbar-btn btn-group">
<a href="#" onclick="setMenuSm('1')" id='toggle-button' class="topbar-menu-toggle btn btn-sm" data-toggle="button">
<span class="ad ad-wand"></span>
</a>
</div>
</li>
</ul>
and the java script:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setMenuSm(){
var cssSelected = $("#toggle-button").hasClass("active");
if (cssSelected !== true) {
setCookie("selectedCSS", "menuopen", 3);
}else{
setCookie("selectedCSS", "menuclose", 3);
}
}
$(document).ready(function() {
getCookie("selectedCSS");
console.log(getCookie("selectedCSS"));
})
... now when click load page console give me "menuopen" and when click on button open gray windows like loading and nothing to do...

Related

jQuery cookie expiring every page

Trying to create a cookie policy where when the button is click, it doesn't display for 30 days, however when the button is clicked it shows again if you refresh the page or change page.
code is below:
obviously I've added in jQuery at the bottom of the page
<div class="cookie-message" id="cookie_banner">
<div class="container">
<h3>This site uses cookies</h3>
<br>
<p>We use cookies to ensure the functionality and performance of the website. We also like to use analytics cookies to monitor and analyse the use of our website. If you are happy with this, click ‘Accept and Continue’ below or view our cookie policy for more information.</p>
<button id="close_cookie_banner" class="btn btn-custom btn-animate btn-pink"><i class="icon-owia-kokroko"></i> Accept and continue</button>
</div>
</div>
jQuery(document).ready(function($) {
let COOKIE_NAME = "divine_cookie_policy";
if ((getCookie(COOKIE_NAME) === "ACCEPTED")){
// Cookie has been set -> Don't show banner
} else {
// No cookie has been set -> show cookie banner
openCookieBanner();
}
$('#close_cookie_banner').on("click", function (event) {
event.stopPropagation();
closeCookieBanner();
});
/**
* openCookieBanner()
*
* Opens the cookie banner
*/
function openCookieBanner () {
$('#cookie_banner').css({
display: "block"
});
} // END openCookieBanner()
/**
* closeCookieBanner()
*
* Closes the cookie banner
*/
function closeCookieBanner () {
// Prep the date.
var interval = 30;
var date = new Date();
date.setTime(date.getTime() + (interval*24*60*60*1000));
var expires = "expires="+ date.toUTCString();
document.cookie = COOKIE_NAME + "=" + "ACCEPTED" + ";" + expires + ";";
// Close the banner
$('#cookie_banner').css({
display: "none"
});
} // END openCookieBanner()
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}(jQuery));
not really sure what else to try
any help is appreciated

Work javascript according to checkbox's state

I have a checkbox that toggle the div and i register the choice to localstore and get it back
But the thing that i can't do is javascript that toggles the div won't see that checkbox's option it's needs to toggle it twice
index.html
<div id="siit" class="sit"></div>
Clock?: <br>
<label class="switch">
<input id="tetik" type="checkbox">
<span class="slider round"></span>
</label>
saat.js
function basla() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('siit').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(basla, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
};
Here is the codepen: https://codepen.io/Etka/pen/BvGKWV
I want this: when user choose to show the clock and leave, when user comes back the javascript will check the checkbox if it's checked will show the clock
When checking the selected state and check the checkbox, also make the clock visible.
// Set the selected state
if (isSaved === "true") {
checkbox.checked = true;
$("#siit").show();
}
Change the css display property of the clock div element #siit to "block" inside your init() function if the checkbox is saved in LocalStorage by changing this:
if (isSaved === "true") {
checkbox.checked = true;
}
To this:
if (isSaved === "true") {
checkbox.checked = true;
document.getElementById("siit").style.display = "block";
}
Here is a CodePen with the above modified code that I forked from your original one: https://codepen.io/andrewl64/pen/LMXNgj?editors=0010

get value for a cookie from a bootrap modal with js

I'm trying to create a modal that has 2 options: yes or no. When a user selects no I will create a condition if value=no then do not display modal.
The issue is that I cannot accomplish it. If is answer is yes I can manipulate the info, I need to display a modal asking a question, get the users answer and based on this and do something every 15 days.
my code is currently not working properly
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
$('#hewant').on('click', function() {
var valyes = $(this).text();
console.log(valyes);
});
$('#hedont').on('click', function() {
var valno = $(this).text();
console.log(valno);
});
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
$("#myModalcashout").modal();
user = "testing me";
if (user != "" && user != null) {
setCookie("username", user, 15);
}
}
}
</script>
<body onload="checkCookie()">
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<div id="hewant" value="yes"> yes i am </div>
<div id="hedont" value="no"> no i dont</div>
</div>
</div>
</div>
</div>
</body>
I restructured your code for you. For starters you only need 1 listener for both buttons, which can be assigned using class on the buttons in the modal (which I changed from div to button tags.
Note: "Run this code snippet" will not work in this sand boxed environment in regards to cookie manipulation so you will have to test this yourself.
There is now a showModal() function that you will call on load that is responsible for showing your modal and attaching a click listener to both buttons on the modal.
When the user clicks yes or no on the modal we get their answer and pass it to checkCookie() function which does as you ask.
I replaced your create and set cookie functions with ones that are tested and work (also added eraseCookie()) there is a great explanation about all 3 functions Here
showModal();
function showModal() {
// only show modal if cookie for the user is null
var user = readCookie("username");
if (user != null) {
alert("Welcome again " + user);
}
else {
user = "testing me";
$("#myModalcashout").modal();
// add listener on buttons
$('.modalButton').on('click', function() {
$('#myModalcashout').modal().hide();
var answer = $(this).val();
console.log(answer);
// create a cookie with the users answer to the modal
createCookie("username", answer, 15);
});
}
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<button class="modalButton" value="yes"> yes i am </button>
<button class="modalButton" value="no"> no i dont</button>
</div>
</div>
</div>
</div>

Keep vertical scroll position when clicking horizontal carousel button

I have a long page with lots of patient data inside an accordion container. At the top of the page there is a carousel with the 7 days of the week. If you click on the left or right arrow, either the previous or following week will show, which in turn, will show the applicable data below in the accordion.
What I need to do is when a user clicks on the left or right arrow, hold the page position on the current accordion section, but still allow the data to be updated. The data currently updates, but the container location may change. That particular container may not have data for one week, but the next week may have data.
I would like to click the arrow and still show the previous container heading.
Ex. I'm on the Hematology container and I click on the right arrow. I want the Hematology container to still be in view, even if there is no content inside.
Here is a screenshot of my page with the carousel and containers.
I know how to do this with anchor tags when dealing with links to different pages, but this is a bit different.
This project uses Angular to asynchronously get the new data for the containers. You can see it below. Thanks
Here is my code for the carousel:
<div id="myCarousel" class="carousel slide russ" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox"></div>
<a class="left carousel-control" href=".russ" role="button" data-slide="prev">
<span class="fa fa-chevron-left" aria-hidden="true"></span>
</a>
<a class="right carousel-control" href=".russ" role="button" data-slide="next" onclick="stopVerticalScrolling()">
<i class="fa fa-chevron-right" aria-hidden="true"></i>
</a>
</div>
My first crack at this:
<script>
function stopVerticalScrolling() {
var scroll = $(window).scrollTop();
$("html").scrollTop(scroll);
//javascript: alert($(window).scrollTop());
}
</script>
AngularJS Code:
function get_sticky_popup_data(timeline, patientMRN, patientSiteid, start, end) {
$http
.get('/API/data/patientdetails/Titlebar/get_admission_data/' + patientSiteid + '?MRN=' + patientMRN)
.success(function(data) {
$scope.carouseldata = data;
build_sticky_table(timeline, $scope.carouseldata, start, end);
var carouselItemTop = $('.displayTableContainer').position();
$('.displayTableContainer').attr('data-offset-top', carouselItemTop.top);
}).error(function(e) {
console.log('error in Ajax call get_admission_data: ' + e.message);
});
}
function build_sticky_table(timeline, items, start, end) {
var startDate = new Date(start.toString());
var endDate = new Date(end.toString());
var dtRotate = new Date(startDate);
var firstWeeksDataObject = new Array(7);
var datediff = ((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
var weeks = (datediff % 7 === 0 ? parseInt((datediff / 7)) + 1 : parseInt((datediff / 7))); // you need this many tables
$('.item').remove();
items.push({
'admit': timeline.admission_range_start,
'datetime': timeline.event_start_date,
'diagnosis': '',
'discharge': timeline.admission_range_end,
'location': timeline.location,
'room_bed': timeline.roombed
});
var isActive = false;
var starting_month_from_query_string = $('#workflow_header_month').val();
var starting_year_from_query_string = $('#workflow_header_year').val();
var match_weekly_data_from_query_string_month_and_year = false;
var previous_match_found = false;
var current_event_start_date = timeline.event_start_date;
if (starting_month_from_query_string !== "0" && starting_year_from_query_string !== "0") {
match_weekly_data_from_query_string_month_and_year = true;
}
for (var i = 0; i <= weeks; i++) {
var name = 'stickytbl' + i.toString();
$('.carousel-inner').append(buildtable(name, i)); //inserts a new table
var hcells = $('#' + name + ' > thead > tr > td');
var brows = $('#' + name + ' > tbody> tr');
$.each(hcells, function (index, item) {
if (index > 0) {
var cell = $(brows[0]).children('td');
var cell2 = $(brows[1]).children('td');
var cell3 = $(brows[2]).children('td');
//set the column data
var currentColumnHeaderDate = dtRotate.getMonth() + 1 + '/' + dtRotate.getDate() + '/' + dtRotate.getFullYear();
var currentColumnHeaderDateWithTime = new Date(currentColumnHeaderDate.toString() + ' 23:59:59');
firstWeeksDataObject[index] = currentColumnHeaderDate;
$(item).text((dtRotate.getMonth()) + 1 + '/' + dtRotate.getDate() + '/' + dtRotate.getFullYear());
//set the row data
if (dtRotate <= currentColumnHeaderDateWithTime) {
var arrayReturn = getDaysData(items, start, end, dtRotate, currentColumnHeaderDate);
//set table row data
$(cell[index]).html(arrayReturn[0]);
$(cell2[index]).html(arrayReturn[1]);
$(cell3[index]).html(arrayReturn[2]);
}
//increment the date
dtRotate.setDate(dtRotate.getDate() + 1);
}
});
}

Cookie returns undefined value in JavaScript

I want to make a cookie to remember a radius that a user can choose. The problem is that the cookie works, but the value of the cookie is undefined. I don't know what I am doing wrong.
The function "opslaan" is linked with a button on the HTML page.
function opslaan()
{
createCookie('radius',document.getElementById("range").value,8);
alert("opgeslagen");
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ')
c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = ";expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name + "=" + value + expires +";path=/";
}
This is the button and the range field where it need to get the value out:
<fieldset class="one-third column">
<label for="">Radius van de kaart (km)</label>
<input type="range"
min="5"
max="20"
value="5"
step="5"
onchange="showValue(this.value)" />
<span id="range">5</span>
<script type="text/javascript">
function showValue(newValue)
{
document.getElementById("range").innerHTML=newValue;
}
</script>
</fieldset>
<script>
alert(readCookie('radius'));
</script>
<div class="one-third column">
<a class="full-width button margin-top25"
href="home.html"
onclick="opslaan()">
Opslaan
</a>
</div>
It seems to be working without the range field and button.
In your case range is a span not an input element, so you need to use innerHTML property to read the contents of that element instead of using value.
use
document.getElementById("range").innerHTML
instead of
document.getElementById("range").value
Ex:
function opslaan()
{
createCookie('radius',document.getElementById("range").innerHTML,8);
}
Demo: Fiddle
document.getElementById("range").value is going to return undefined. Which is your problem here. Try using document.getElementById("range").innerHTML

Categories

Resources