Display and delete multiple cookies in Javascript - javascript

I want to display the last three search values on the website using javascript cookies. I store last three values but when I display in view it displays everything together. I have two question.
I want to display the values separately inside the href. So the user can click and search again.
Actual output
1=Dubai; 2=India; 3=SriLanka <span class='rmvcookie'>x</span>
Expecting output
<a href='abc.com?location=Dubai'>Dubai</a><span class='rmvcookie'>x</span>
<a href='abc.com?location=India'>India</a><span class='rmvcookie'>x</span>
<a href='abc.com?location=SriLanka'>SriLanka</a><span class='rmvcookie'>x</span>
I created removeCookies function but it removes all the cookies at once. I want to remove the cookies individually.
This website does the same. makemytrip.ae/holidays-india Search by any destination. It stores the values and you can remove it individually.
I tried last two days and couldn't get the right code. Can anyone help me? Please.
JavaScript
var num = 1;
function addCookie() {
var searchvalue = document.getElementsByClassName("cookiename")[0].value;
document.cookie = num + "=" + searchvalue;
if (num >= 3) { //Limit for last three search value
num = 1;
} else {
num++;
}
var result = document.cookie;
document.getElementById("list").innerHTML = "<a href='abc.com?location=" + result + "'>" + result + "</a> <span class='rmvcookie' onclick='removeCookies()'>x</span>";
}
function listCookies() {
var result = document.cookie;
document.getElementById("list").innerHTML = "<a href='abc.com?location=" + result + "'>" + result + "</a> <span class='rmvcookie' onclick='removeCookies()'>x</span>";
}
window.onload = function() {
listCookies();
};
function removeCookies() {
var res = document.cookie;
var multiple = res.split(";");
for (var i = 0; i < multiple.length; i++) {
var key = multiple[i].split("=");
document.cookie = key[0] + "=; expires=Thu, 28 May 2030 00:00:00 UTC";
}
}
HTML
<input type="text" id="searchTxt" class="cookiename" name="asd">
<button onclick='addCookie()'>ADD</button><br>
<button onclick='removeCookies()'>REMOVE</button>
<h1>Cookies List</h1>
<p id="list"></p>
View

I wrote a solution on codepen - https://codepen.io/darius9171/pen/JBBRaz
Stackoverflow does not allow you to work in snippets with cookies, but requires you to write code when you specify a link to codepen. So don't pay attention to the snippet :D
//set cookies
const cookies = ['Dubai', 'India', 'SriLanka'];
cookies.forEach((name, i) => document.cookie = `${i+1}=${name};`);
//render
const list = document.querySelector('.list');
document.cookie.split('; ').forEach(cookie => {
const pair = cookie.split('=');
list.innerHTML += `<div class="cookie" data-name="${pair[0]}">${pair[1]} <span class='rmvcookie'>x</span></div>`
})
document.querySelectorAll('.rmvcookie').forEach(span => {
span.addEventListener('click', (event) => {
const parent = event.currentTarget.parentNode;
document.cookie = `${parent.dataset.name}=; expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
parent.parentNode.removeChild(parent);
})
})
span {
color: blue;
cursor: pointer;
}
<div class="list">
</div>

Related

I was practicing a way to loop numbers to create a times table but the loop only runs one time

I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>

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

Using multiple checkboxes, all made by a javascript function, with Javascript

A function uses Google Maps API results to create a list of places (hotels etc.) besides each one there is a checkbox:
if(place['rating']) {
LocationName = place['name'];
LocationString += `<div class="input-group" id="Location-checkbox-${[i]}">
<span value=${[i]} class="input-group-addon">
<input type="checkbox" name="choice"
id="checkboxes" aria-label="..." onclick="chooseSelection(${[i]})">
</span>
<li id="Location-${[i]}" class="list-group-
item"><strong id="locationName-${[i]}">${LocationName}</strong><br>`;
if(place['rating']) {
var LocationRating = place['rating'];
LocationString += `rating: <span
id="locationRating-${[i]}">${LocationRating}</span><br>`;
} else {
var LocationRating = 'This place has no rating';
LocationString += LocationRating;
}
if(place['user_ratings_total']) {
var LocationUsers = place['user_ratings_total'];
LocationString += `based on ${LocationUsers} reviews</li></div>`;
} else {
var LocationUsers = '</li></div>';
LocationString += LocationUsers;
}
htmlString += LocationString;
I then need to add the ones the user chooses into an temporary array:
var temporarySelection = "";
var placeSelection = "";
var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
temporarySelection += `<div class="input-group" id="Hotel-chosen">
<li class="list-group-item">
<strong>${locationName.innerHTML}</strong><br>`;
var locationRating = document.getElementById('locationRating-' +
resultIndex);
temporarySelection += `rating: ${locationRating.innerHTML}</li></div>`
}
Lastly, I need to move the temporary selection into ANOTHER array.
My problem is that, at the moment, the checkboxes are just working like buttons. Every time you click it, it just adds another one to the array. I want to only add the ones to the array that are ticked when the Next button is clicked (not shown in the code).
Any advice?

Real time agenda with javascript and json

I have a div on a website that needs to be a real time agenda for a list of events. I have the events loaded through a json file and am using javascript to populate the div with the data from the file.
The problem is that the data displays stacked item by item in one column within a div, I need to now split the div into three separate columns/divs. One for events happening now, next, and coming soon. Ex) one event is at 7am, next is 7:30, and coming soon is 8am.
But I am not able to select each item and move it using css since the code just populates by one item upon page load and I cannot see an index for each item (video side content item) over and over to display what events are necessary.
This would be a lot easier if I could just format the items being populated into three separate columns through css, but I can't figure out how to do this.
By the way this site is written using FlexBox, hence why there is a "row" in one of the divs.
Also can someone please point in the right direction as to how to get this to be real time? Or any other helpful solution that could achieve this?
Thanks in advance for any help.
picture of what I'm trying to do
Function to populate the data
function agendaRealTimeUpdate() {
if ($('.real-time-agenda').length !== 0) {
videoSideContentType = 'agenda';
$.getJSON("ac.json", function(data) {
var sessions = data.session;
var contentString = '';
var currentSessionIndex;
var currentSession;
var currentTime;
var currentDay;
var title;
var time;
var room;
var description;
var d;
var i = 0;
d = new Date();
//gets the current time and returns it in a string with 3-4 digits EX: "1000" = 10 am
currentTime = parseInt(d.getHours().toString() + ((d.getMinutes() < 10 ? '0' : '') + d.getMinutes()).toString());
currentDay = d.getDate();
// this loop runs as long as we haven't figured out which session matches the time
while (currentSessionIndex === undefined && i < sessions.length) {
//this takes the current time and compares it to the sessions start and end times
if ((currentTime >= sessions[i].startTime && currentTime <= sessions[i].endTime) &&
currentDay === sessions[i].day &&
sessions[i].track === "none")
{
currentSessionIndex = i;
}
i++;
}
if (currentSessionIndex === undefined) {
currentSessionIndex = 0;
}
// This function finds the sessions that come after the identified current session
function findNextSessions() {
var sessionsCopy = sessions.slice(); //make a copy of the sessions array so we aren't altering it when we remove indexes
for (var z = 0; z < 2; z++) {
var index = currentSessionIndex + z;
// breaks out of the loop if the next session is undefined
if (sessionsCopy[index] === undefined) {
z = 2;
}
currentSession = sessionsCopy[index];
// loops through the sessions and if the session has a track it is removed from the sessionsCopy array
while (currentSession.track !== "none") {
console.log('has a track: ' + currentSession.track);
sessionsCopy.splice(index, 1);
currentSession = sessionsCopy[index];
}
time = currentSession.timeString !== undefined ? "<div class='video-side-content__time'><b>Time:</b> " + currentSession.timeString + "</div>" : '';
room = currentSession.room !== undefined ? "<div class='video-side-content__room'><b>Room:</b> " + currentSession.room + "</div>" : '';
title = currentSession.title !== undefined ? "<div class='video-side-content__secondary-title'>" + currentSession.title + "</div>" : '';
description = currentSession.content !== undefined ? "<div class='video-side-content__content'>" + currentSession.content + "</div>" : '';
contentString += "<div class='video-side-content__item'>" + time + room + title + description + "</div>";
}
}
findNextSessions();
$('.real-time-agenda').html(contentString);
});
}
}
Div I'm working with
<div class="row__item">
<h2 class="video-side-content__title"><img src="img/agenda-icon.png"> Thursday. Sept. 22</h2>
<div class="row__flex-container">
<div class="row__item video-side-content__strip video-side-content__strip-left"> </div>
<div class="row__item video-side-content__row">
<div class="video-side-content">
<div class="video-side-content__items">
<div class="video-side-content__item">
<h2 class="count-down__sub-header"><br>
SHOWING NOW</h2><br>
<div class="real-time-agenda">
<!--data populates upon page load from the json file
It lays the data out as: Time, Title, Room, Description-->
</div>
<br>
</div>
</div>
</div>
</div>
</div>
</div>

How to Change color of a text after a time period?

I have created a notice board. I want to show the notices in Red color for the first 48 hours. After 48 hour the color of the Notices will be changed. Now what should i change or add in my code?
HTML body for the notice board -
<div class="col-md-4">
<div class="widget-item" style="padding-top:0px;margin-top:0px;">
<div class="widget-main-title">
<h4 class="widget-title">Notice Board</h4>
</div> <!-- /.widget-main-title -->
<marquee id="dvNotice" FACE="courier" BEHAVIOR="SCROLL" height="247px" onmouseout="this.setAttribute('scrollamount', 2, 0);" onmouseover="this.setAttribute('scrollamount', 0, 0);" scrollamount="2" direction="up" style="text-align: left;">
<%--<div class="widget-inner" id="dvNotice">
</div> --%><!-- /.widget-inner -->
</marquee>
<!-- /.request-information -->
</div> <!-- /.widget-item -->
</div>
JQuery/JavaScript -
$(document).ready(function () {
PageMethods.loadNotice('', loadNoticeSuccess);
});
function loadNoticeSuccess(result) {
$("#dvNotice").html('');
var html = "";
for (var i = 0; i < result.length; i++) {
var month_value = result[i].PublishedDate.getMonth();
var day_value = result[i].PublishedDate.getDate();
html += "<div class=\"event-small-list clearfix\">";
html += "<div class=\"calendar-small\"><span class=\"s-month\">" + months[month_value] + "</span><span class=\"s-date\">" + day_value + "</span></div>";
//html += "<div class=\"event-small-details\"><h5 class=\"event-small-title\">" + result[i].Title + "</h5><p class=\"event-small-meta small-text\">" + result[i].Description + "</p></div></div>";
html += "<div class=\"event-small-details\"><h5 class=\"event-small-title\">" + result[i].Title + "</h5><p class=\"event-small-meta small-text\"></p></div></div>";
}
html += "<div class=\"event-small-list clearfix\" style=\"text-align:right;padding:0;\">More</div>";
$("#dvNotice").append(html);
}
C# Code Behind for loading the notice board -
[WebMethod]
public static List<Notice> loadNotice(string value)
{
IList<Notice> notice = NoticeManager.GetTopPublishedNotice();
if (notice == null)
{
notice = new List<Notice>();
}
return notice.ToList();
}
I assume you are using some CMS to add these notices. One option is to check difference between notice/content creation time and now on page load. This can be done easily through javascript get Time function.
If you don't have such value then simply add it to you CMS, to store metadata of creation date and time. Most CMS I have encountered have such possibilities.
Hope this theory will help.
Can you please try this code after appending the html to the div dvNotice ,
setTimeout(function () {
$('#dvNotice').css('color','yellow');
}, 172800000);
I'm leveraging the function from this answer to calculate the difference of two dates, based on the assumption that 48 hours == 2 days
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// tweaked OP code
function loadNoticeSuccess(result) {
$("#dvNotice").html('');
var html = "";
for (var i = 0; i < result.length; i++) {
var isPast48Hours = dateDiffInDays(new Date(), result[i].PublishedDate) > 2;
if (isPast48Hours) { /*setup html for default color*/ }
else { /*setup html for red color */ }
// rest of code, using the html you setup above for the variable color
}
}
What's missing here is a real-time verification (and reaction, switching the colors) of the age of the entry: if the page is loaded 47 hours and 59 minutes after the published date, the entry will be red and stay red.

Categories

Resources