Keep vertical scroll position when clicking horizontal carousel button - javascript

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

Related

Assigning a class to an element once it's appended

So I currently have slider that the user can dynamically fill upon uploading images. I'm using bootstrap for the slider which requires the first slide to have the class "active" in order to work, however when I try to assign that class to the first slide using
"if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
it doesn't recognize the slide id and assigns null to the value, returning "cannot setAttribute of null".
Any advice?
HTML
<div id="slideshow-container">
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<ul class="carousel-inner" id ="carousel-inner">
</ul>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
JS
window.onload = function() {
$('#_uploadImages').click(function () {
$('#_imagesInput').click();
setTimeout(activeness(), 5000)
});
$('#_imagesInput').on('change', function () {
handleFileSelect();
});
}
function handleFileSelect() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files; //FileList object
var output = document.getElementById("carousel-inner");
var arrFilesCount = [];
var start = $(output).find('li').length;
var end = start+ files.length;
var nonImgCount = 0;
var slide1 = document.getElementById("slide1")
var display = document.getElementById("displayImg")
for (var i = start; i < end; i++) {
arrFilesCount.push(i); // push to array
}
if(start !== 0){
$(output).find('li > nav > a.prev').first().attr('href','#slide-' + (end-1));
$(output).find('li > nav > a.next').last().attr('href','#slide-'+start);
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image')) {nonImgCount++; continue;}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
current_i = arrFilesCount.shift();
if (current_i === 0) {
prev_i = files.length - 1; //This is for the first element. The previous slide will be the last image. (i=length-1)
} else {
prev_i = current_i - 1;
}
if (arrFilesCount.length - nonImgCount === 0) {
next_i = 0;
} else {
next_i = current_i + 1; //This is for the last element. The next slide will be the first image (i=0)
}
display.src = picFile.result
output.innerHTML = output.innerHTML + '<li id="slide-' + current_i + '" class="carousel-item">' + "<img class='d-block w-100' src='" + picFile.result + "'" + "title=''/>" + '</li>'; // TODO: Enter Title
});
//Read the image
picReader.readAsDataURL(file);
}
if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
} else {
console.log("Your browser does not support File API");
}
}

set cookie for toggle menu

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...

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 link pagination to pagescroll in jquery?

I have created a carousel in javascript to show multiple contents either by using page scroll or by clicking a button. I have used viewpager.js for this purpose. I have added a pagination at the bottom which works fine when the buttons are clicked. I am unable to figure out how to link it to the page scroll. Any help is appreciated. My code:
HTML
<div id='prev'>
<button id="btn-prev"><img src='img/orange-towards-left.png'></button>
</div>
<div class='pager'>
<div class='pager_items' id='info'>
</div>
</div>
<div id='next'>
<button id="btn-next"><img src='img/orange-towards-right.png'></button>
</div>
<div id='pagination'>
<ul></ul>
</div>
JS
item_container = document.querySelector('.pager_items');
view_pager_elem = document.querySelector('.pager');
w = view_pager_elem.getBoundingClientRect().width;
items = payerAccArr.length;
item_container.style.width = (items * 100)+ '%';
var child_width = (100 / items) + '%';
var html = "";
document.getElementById('monthInfo').innerHTML=payerAccArr[0].DateKey + " Bill Amount ";
for (var i = 0; i < items; i++) {
html += "<div class=toggle><h4>Payer Account Name</h4> <ul> <li>" + payerAccArr[i].PayerAccountName +
"</li></ul> _______________ <ul><li> "+(payerAccArr[i].TotalAmount).toFixed(2) +
" USD</li> </ul></div>";
}
item_container.innerHTML = html;
for(var i=0;i<items;i++)
item_container.children[i].style.width = child_width;
var htmlStr='<li class="current"></li>';
for(var i=0;i<items-1;i++){
htmlStr += '<li></li>';
}
$('#pagination ul').html(htmlStr);
vp = new ViewPager(view_pager_elem, {
pages: item_container.children.length,
vertical: false,
onPageScroll : function (scrollInfo) {
offset = -scrollInfo.totalOffset;
invalidateScroll();
},
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
}
});
window.addEventListener('resize', function () {
w = view_pager_elem.getBoundingClientRect().width;
invalidateScroll();
});
document.getElementById('btn-prev').addEventListener('click', function (){
vp.previous();
if(index>0){
createDoughnutChart(index--);
}
var li = jQuery("li.current");
if (li.length){
var $prev = li.prev();
if($prev.length == 0)
$prev = $("#pagination li").last().addClass("current");
li.removeClass("current");
$prev.addClass("current");
}
});
Similar code for the next button also has been written.
This issue got solved. I made a change to the onPageChange function by adding the following code. I am now able to link it to both the page scroll and the buttons.
JS:
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
// console.log('page', page);
var li = $("li.current");
var curIndex = li.index();
if(li.length){
var $prev = li.prev();
var $next = li.next();
if(page == $prev.index()){
li.removeClass("current");
$prev.addClass("current");
}
if(page==$next.index()){
li.removeClass("current");
$next.addClass("current");
}
}
}

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