I am trying to create collapsible DIVs that react to links being clicked. I found how to do this using "next" but I wanted to put the links in a separate area. I came up with this which works...
JSFiddle - Works
function navLink(classs) {
this.classs = classs;
}
var homeLink = new navLink(".content-home");
var aboutLink = new navLink(".content-about");
var contactLink = new navLink(".content-contact");
var lastOpen = null;
$('.home').click(function() {
if(lastOpen !== null) {
if(lastOpen === homeLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-home').slideToggle('slow');
lastOpen = homeLink;
}
);
$('.about').click(function() {
if(lastOpen !== null) {
if(lastOpen === aboutLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-about').slideToggle('slow');
lastOpen = aboutLink;
}
);
$('.contact').click(function() {
if(lastOpen !== null) {
if(lastOpen === contactLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-contact').slideToggle('slow');
lastOpen = contactLink;
}
);
I am now trying to create the same result but with a single function instead of one for each link. This is what I came up with....
function navLink(contentClass, linkClass, linkId) {
this.contentClass = contentClass;
this.linkClass = linkClass;
this.linkId = linkId;
}
var navs = [];
navs[0] = new navLink(".content-home", "nav", "home");
navs[1] = new navLink(".content-about", "nav", "about");
navs[2] = new navLink(".content-contact", "nav", "contact");
var lastOpen = null;
$('.nav').click(function(event) {
//loop through link objects
var i;
for (i = 0; i < (navsLength + 1); i++) {
//find link object that matches link clicked
if (event.target.id === navs[i].linkId) {
//if there is a window opened, close it
if (lastOpen !== null) {
//unless it is the link that was clicked
if (lastOpen === navs[i]) {
return;
} else {
//close it
$(lastOpen.contentClass).slideToggle('fast');
}
}
//open the content that correlates to the link clicked
$(navs[i].contentClass).slideToggle('slow');
navs[i] = lastOpen;
}
}
});
JSFiddle - Doesn't Work
No errors so I assume that I am just doing this completely wrong. I've been working with Javascript for only about a week now. I've taken what I've learned about arrays and JQuery events and tried to apply them here. I assume I'm way off. Thoughts? Thanks
You just forgot to define navsLength:
var navsLength=navs.length;
Of course you could also replace it with a $().each loop as you're using jQuery.
[Update] Two other errors I corrected:
lastOpen=navs[i];
for(i=0; i < navsLength ; i++)
Demo: http://jsfiddle.net/jMzPJ/4/
Try:
var current, show = function(){
var id = this.id,
doShow = function() {
current = id;
$(".content-" + id).slideToggle('slow');
},
toHide = current && ".content-" + current;
if(current === id){ //Same link.
return;
}
toHide ? $(toHide).slideToggle('fast', doShow): doShow();;
};
$("#nav").on("click", ".nav", show);
http://jsfiddle.net/tarabyte/jMzPJ/5/
Related
I'm stuck as to why I can't get an AddEventListener click event to work on a set of images that appear in a modal. I had them working before before the modal aspect was involve, but I'm not sure that the modal broke the image click event either.
Here is the function in question, which is called within a massive document.addEventListener("DOMContentLoaded", function (event) function:
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.addEventListener('click', function (e) {
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
// console.log("childItems.forEach"); we get into here
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
// console.log("no tags selected"); we get to here
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
//console.log("before adding click to images"); we get here
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
attachClick();
//open a modal to show off the portfolio pieces for the selected client
var tingleModal = document.querySelector('.tingle-modal');
drawer.className = 'drawer';
var portfolioModal = new tingle.modal({
onOpen: function() {
if(tingleModal){
tingleModal.remove();
}
console.log('modal open');
},
onClose: function() {
console.log('modal closed');
//tingleModal.remove();
}
});
e.preventDefault();
portfolioModal.open();
portfolioModal.setContent(document.querySelector('.drawer-content').innerHTML);
});
});
};
And the specific bit that I'm having trouble with:
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
I tried removing the e.PreventDefault() bit but that didn't solve the issue. I know the images are being created, so the img variable isn't empty. I feel like the addEventListener is setup correctly. I also tried moving that bit up just under the img.src = item.thumb line, but no luck. For Some reason, the click event just will not trigger for the images.
So if I understand correctly, you have a modal that lies above the images (it has a higher z-index)? Well in this case the clicks are not reaching the images as they will hit the modal. You can pass clicks through elements that lie above by applying the css property pointer-events: none; to the modal, but thats somehow controversial to what a modal is intended to do.
Are the images present in the modal on DOMContentLoaded? You may be able to try delegating the handling of clicks to a parent element if that's the case.
You can try the delegation approach shown here: Vanilla JavaScript Event Delegation
I'm currently working on a project, where I'm using the following slider in the overal site:
S3Slider
For the particular page I'm currently working on I'm also making use of Walter Zorns' Drag&Drop image library. (Link Here)
Now when I start to make use of the SET_DHTML function, which is required for using the D&D library, my slider starts throwing errors:
Uncaught TypeError: Cannot read property 'contains' of null
The line number given, sends me to the following line:
if($(itemsSpan[currNo]).css('bottom') == 0) {
Which lies in the following piece of code:
s3Slider = function(id, vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 2000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderTopstory");
var itemsSpan = $("#sliderContent .sliderTopstory span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
/* This line -> */if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function( ) {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
Why is this error being thrown?
Thanks.
I think your problem lies in these two lines:
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
If jQuery doesn't find the item in the array, it's going to send you a value of -1 (on the top line) which will then be changed to 0 because you added 1. Now, if currNo is 0 on the second line, it's going to change it back to -1, which will return you undefined. Maybe try and change it to do this instead:
var currNo = jQuery.inArray(current, items);
if (currNo === items.length - 1) {
currNo = 0;
}
I'm not positive this is the problem, but I can see this becoming an issue if it's not the problem you're currently having.
This is a design portfolio page. On load, the JSON data is retrieved via ajax, and one of the keys is used to generate a list of '.project-links' (no project is displayed on load, and the project images are loaded only when a project is selected (see showProj function)). My question regards the fadein/fadeout: the images are still painting onto the screen after the fade in completes, despite the project content being defined/loaded within the fadeOut callback; can someone please enlighten me as to how I can tweak this so that the fadeIn won't run until the projImages are loaded?
Thank you, svs.
function ajaxReq() {
var request = new XMLHttpRequest();
return request;
}
function makeLinks(projects) { // result = getJsonData > request.responseText
var projectList = document.getElementById("project-list");
for (var project in projects) {
if (projects[project].status !== "DNU") {
var projectId = projects[project].id;
var listItem = "<li><a class=\"project-link\" id=\""+projects[project].project+"\" href=\"#\">" + projects[project].project + "</a></li>";
projectList.innerHTML += listItem;
} // if !DNU
}
// ADD EVENT LISTENERS
var projLink = document.getElementsByClassName("project-link");
for (var i = 0; i < projLink.length; i++) {
var projId = projLink[i].id;
//projLink[i].dataset.projIx = [i];
projLink[i].addEventListener("click", showProject, false);
}
var showNext = document.getElementById("show-next");
var showPrev = document.getElementById("show-previous");
showNext.addEventListener("click", showProject, false);
showPrev.addEventListener("click", showProject, false);
// ARROW KEYS [not invoking the showProject function]
$(document).keydown(function(e) {
if(e.which==37) { // LEFT arrow
$(showPrev).click(showProject);
console.log("previous");
} else
if(e.which==39) { // RIGHT arrow
$(showNext).click(showProject);
console.log("next");
}
})
function showProject(projId) {
var intro = document.getElementById("intro");
if (intro) {
intro.parentNode.removeChild(intro);
}
projId.preventDefault();
var projLinks = document.getElementsByClassName("project-link"); // array
var selIx = $(".selected").index();
// ###### CLICK PREVIOUS/NEXT ######
if (this.id === "show-previous" || this.id === "show-next") {
// 1a. if nothing is .selected
if (selIx < 0) {
if (this.id === "show-previous") {
var selIx = projLinks.length-1;
}
else if (this.id === "show-next") {
var selIx = 0;
}
}
// 1b. if .selected:
else if (selIx > -1) {
if (this.id === "show-previous") {
if (selIx === 0) { // if # first slide
selIx = projLinks.length-1;
}
else {
selIx --;
}
}
else if (this.id === "show-next") {
if (selIx === projLinks.length-1) { // if # last slide
selIx = 0;
}
else {
selIx ++;
}
}
}
var selProjLi = projLinks[selIx]; // => li
} // click previous/next
// ###### CLICK .project-link ######
else if (this.id !== "show-previous" && this.id !== "show-next") {
var selIx = $(this).closest("li").index();
}
// FADE OUT, CALLBACK: LOAD NEW PROJECT
$("#project-display").fadeTo(450, 0.0, function() {
// ###### ALL ######
$(".selected").removeClass("selected");
var projId = projLink[selIx].id;
var selProjLi = projLink[selIx].parentElement;
selProjLi.className = "selected";
var projectDisplay = document.getElementById("project-display");
// set vars for the project display elements:
var projName = document.getElementById("project-name"); // h3
var projTools = document.getElementById("project-tools");
var projNotes = document.getElementById("project-notes");
var projImages = document.getElementById("project-images");
// disappear the metadata elements 'cause sometimes they'll be empty
projTools.style.display = "none";
projNotes.style.display = "none";
testimonial.style.display = "none";
for (var project in projects) { // 'Projects array' -> project
if (projects[project].project === projId) {
var activeProj = projects[project];
projName.innerHTML = activeProj.project;
// maintain centered display of project-metadata: check for a value, else the element remains hidden
if(activeProj["tools used"]) {
projTools.style.display = "inline-block";
projTools.innerHTML = activeProj["tools used"];
}
if(activeProj.notes) {
projNotes.style.display = "inline-block";
projNotes.innerHTML = activeProj.notes;
}
if(activeProj.testimonial) {
testimonial.style.display = "inline-block";
testimonial.innerHTML = activeProj.testimonial;
}
// HOW TO ENSURE THESE ARE ALREADY LOADED ***BEFORE #project-display FADES IN***
projImages.innerHTML = "";
for (var i = 0; i < activeProj.images.length; i++ ) {
projImages.innerHTML += "<img src=\"" + activeProj.images[i].url + "\" />";
}
} // if project id ...
} // for (var obj in data)
}) // fade out
$("#project-display").fadeTo(600, 1.0);
} // showProject
} // makeLinks
function getJsonData() {
var request = ajaxReq();
request.open("GET", "/json/projects.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//makeLinks(request.responseText);
var projects = JSON.parse(request.responseText);
var projects = projects["Projects"];
makeLinks(projects); // makeLinks = callback
return projects;
}
}
} // onreadystatechange
} // getJsonData
getJsonData(makeLinks);
You can add a load event to the images and run the fadeOut when all the images are loaded.
Since you are going to need multiple images to complete loading, I chose to keep track of which loads are complete using an array of jQuery.Deferred() objects. Once all the Deferreds are resolved then you can run the fade animation.
Here's a function that should work:
function fadeWhenReady(projImages, images) {
projImages.innerHTML = "";
var loads = []; //create holding bin for deferred calls
//create images and attach load events
for (var i = 0; i < activeProj.images.length; i++ ) {
var deferred = $.Deferred();
var img = $("<img src=\"" + activeProj.images[i].url + "\" />");
img.on("load", function() { deferred.resolve() }); //after image load, resolve deferred
loads.push(deferred.promise()); //add the deferred event to the array
img.appendTo(projImages); //append image to the page
}
//when all deferreds are resolved, then apply the fade
$.when.apply($, loads).done(function() {
$("#project-display").fadeTo(600, 1.0);
});
}
In your function showProject remove your call to $("#project-display").fadeTo(600, 1.0); and replace the lines below with a call to the fadeWhenReady function.
projImages.innerHTML = "";
for (var i = 0; i < activeProj.images.length; i++ ) {
projImages.innerHTML += "<img src=\"" + activeProj.images[i].url + "\" />";
}
P.S. You are using a strange mix of jQuery and vanilla javascript. The calls to document.getElementById() don't mind me so much, but I'd certainly recommend replacing your XMLHttpRequests with jQuery.ajax().
I have running script which moves the tr elements from one container to another on double click. But i have below mentioned issues:
1) If we do are very quick double-click on elements than it moves but its values doesn't come, it shows empty tags.
2) I want to change the background color on double click and it color should remove when we click outside or another elements.
<script>
$(function () {
function initTabelMgmt() {
selectInvitees();
moveSelectedInvitees();
deleteInvitees();
//scrollOpen();
}
var tmContainer = $("div.cv-tm-body");
var toggleAssignBtn = tmContainer.find('.cv-move-items button');
/*
function scrollOpen() {
var position = $('div.cv-item li.open').first().position();
var offsetTop = $('div.cv-tm-col-r .cv-helper-grid-overflow').scrollTop();
var unitHeight = $('div.cv-item li.open').first().height();
var containerHeight = $('div.cv-tm-col-r .cv-helper-grid-overflow').height();
var scrollAmount = offsetTop + position.top;
if ((offsetTop - position.top) <= 0 && (offsetTop - position.top) >= (-containerHeight + unitHeight)) {
//do nothing
} else {
$('div.cv-tm-col-r .cv-helper-grid-overflow').animate({
scrollTop: scrollAmount
});
}
};
*/
// scrollOpen end
function selectInvitees() {
//select items from invitee list
var startIndex, endIndex;
var dbclick = false;
tmContainer.find("table.cv-invitees").on('click', 'tr', function (e) {
var row = $(this);
setTimeout(function () {
//singleclick functionality start.
if (dbclick == false) {
if (!row.is('.assigned')) {
toggleAssignBtn.removeClass('is-disabled');
if (e.shiftKey) {
row.parents('.cv-invitees').find('tr').removeClass('selected');
endIndex = row.parents('.cv-invitees').find('tr').index(this);
var range = row.closest('table').find('tr').slice(Math.min(startIndex, endIndex), Math.max(startIndex, endIndex) + 1).not('.assigned');
range.addClass('selected');
} else if (e.ctrlKey) {
startIndex = row.parents('.cv-invitees').find('tr').index(this);
row.toggleClass('selected');
} else {
startIndex = row.parents('.cv-invitees').find('tr').index(this);
row.parents('.cv-invitees').find('tr').not(this).removeClass('selected');
row.toggleClass('selected');
}
}
}
}, 200)
})
.dblclick(function () {
dbclick = true
//doubleclick functionality start.
toggleAssignBtn.addClass('is-disabled');
function moveSelectedInviteesDBClick() {
var row = tmContainer.find("table.cv-invitees tr.selected");
if (!row.is('.assigned')) {
var allOpenSeat = $('.cv-item .open');
var numberOpen = allOpenSeat.length;
var name = row.find("td").eq(0).text();;
var company = row.find("td").eq(1).text();
var addedInvitees = [];
allOpenSeat.each(function (index) {
if (index < 1) {
var openSeat = $(this);
openSeat.find('.name').text(name);
if (company != '') {
openSeat.find('.company').addClass('show').text(company);
}
var seatAssignment = new Object();
seatAssignment.company = "";
addedInvitees.push(seatAssignment);
openSeat.removeClass('open');
}
row.remove();
});
}
} // moveSelectedInviteesDBClick
moveSelectedInviteesDBClick();
setTimeout(function () {
dbclick = false
}, 300)
});
} // selectInvitees end
function moveSelectedInvitees() {
//move invitees from left to right
tmContainer.find('button.cvf-moveright').click(function () {
var selectedItem = $('.cv-invitees .selected');
var allOpenSeat = $('.cv-item .open');
var numberSelected = selectedItem.length;
var numberOpen = allOpenSeat.length;
var errorMsg = tmContainer.prev('.cv-alert-error');
if (numberSelected > numberOpen) {
errorMsg.removeClass('is-hidden');
} else {
var name;
var company;
var invitee = [];
var selectedInvitees = [];
var count = 0;
selectedItem.each(function () {
var $this = $(this);
name = $this.find("td").eq(0).text();
company = $this.find("td").eq(1).text();
invitee = [name, company];
selectedInvitees.push(invitee);
count = count + 1;
i = 0;
$this.remove();
});
var addedInvitees = [];
var items = $('div.cv-item li');
var seatItems = $('div.cv-order li');
allOpenSeat.each(function (index) {
if (index < count) {
var openSeat = $(this);
openSeat.find('.name').text(selectedInvitees[index][0]);
if (selectedInvitees[index][1] != '') {
openSeat.find('.company').addClass('show').text(selectedInvitees[index][1]);
}
var seatAssignment = new Object();
seatAssignment.company = "";
addedInvitees.push(seatAssignment);
//selectedInvitees.shift();
openSeat.removeClass('open');
}
});
selectedInvitees = [];
}
toggleAssignBtn.addClass('is-disabled');
});
} // moveSelectedInvitees end
function deleteInvitees() {
//move invitees from left to right
tmContainer.find('div.cv-tm-col-r .cv-icon-remove').click(function () {
//delete seat assignment
var icon = $(this);
var idx = $('.ui-sortable li').index(icon.parent());
icon.parent().fadeTo(0, 0).addClass('open').find('.name').text('Open').end().fadeTo(750, 1);
icon.parent().find('.company').removeClass('show').text('');
// icon.parent().find('.entitystub').text('00000000-0000-0000-0000-000000000000');
// icon.parent().find('.entitytype').text('0');
// icon.parent().find('.pipe').remove();
// icon.hide();
// var testSeat = $('.seat-numbers li').get(idx);
//var seatStub = j$.trim(j$(testSeat).find('.seatstub').text());
//var input = { 'seatStub': seatStub };
//AssignSeats(input, "/Subscribers/WS/SeatAssignmentService.asmx/DeleteRegistrant");
});
}
initTabelMgmt();
}); // document.ready end
</script>
Your code looks pretty nice. You should also use in order to register from jQuery a single click event the native method .click(...). So please change the following line
tmContainer.find("table.cv-invitees").on('click', 'tr', function (e) {
To:
tmContainer.find("table.cv-invitees").click(function (e) {
and everything should work fine. For some strange reasons the function
$("#someelement").on("click", ...);
does not work always, only sometimes. JQuery officially recommends you to use the native functions for predefined events (such as onclick, onkeyup, onchange etc.) because of this strange behavior.
Edit:
If dblick does not work now, then make 2 lines please, like this:
tmContainer.find("table.cv-invitees").click(function (e) {
// [...]
;
tmContainer.find("table.cv-invitees").dbclick(function (e) {
// [...]
Edit2:
If it does not work, too, then please remove the single click event listener when you are in the .click() closure. Because if this happens, jQuery´s behavior is to treat it always as a single click. So, in other words dblick() will never be triggered, because .click() will always happens before. And then jQuery won´t count up to 2 fast clicks. Expect the unexpected^^
Edit3: This is the full code, which should hopefully work now as it is:
$(function ()
{
function initTabelMgmt()
{
selectInvitees();
moveSelectedInvitees();
deleteInvitees();
//scrollOpen();
}
var tmContainer = $("div.cv-tm-body");
var toggleAssignBtn = tmContainer.find('.cv-move-items button');
var iClickCounter = 0;
var dtFirstClick, dtSecondClick;
/*
function scrollOpen() {
var position = $('div.cv-item li.open').first().position();
var offsetTop = $('div.cv-tm-col-r .cv-helper-grid-overflow').scrollTop();
var unitHeight = $('div.cv-item li.open').first().height();
var containerHeight = $('div.cv-tm-col-r .cv-helper-grid-overflow').height();
var scrollAmount = offsetTop + position.top;
if ((offsetTop - position.top) <= 0 && (offsetTop - position.top) >= (-containerHeight + unitHeight)) {
//do nothing
} else {
$('div.cv-tm-col-r .cv-helper-grid-overflow').animate({
scrollTop: scrollAmount
});
}
};
*/
// scrollOpen end
function selectInvitees()
{
//select items from invitee list
var startIndex, endIndex;
var dbclick = false;
tmContainer.find("table.cv-invitees").click(function(e)
{
iClickCounter++;
if (iClickCounter === 1)
{
dtFirstClick = new Date();
var row = $(this);
window.setTimeout(function ()
{
//singleclick functionality start.
if (dbclick == false)
{
if (!row.is('.assigned'))
{
toggleAssignBtn.removeClass('is-disabled');
if (e.shiftKey)
{
row.parents('.cv-invitees').find('tr').removeClass('selected');
endIndex = row.parents('.cv-invitees').find('tr').index(this);
var range = row.closest('table').find('tr').slice(Math.min(startIndex, endIndex), Math.max(startIndex, endIndex) + 1).not('.assigned');
range.addClass('selected');
}
else if (e.ctrlKey)
{
startIndex = row.parents('.cv-invitees').find('tr').index(this);
row.toggleClass('selected');
}
else
{
startIndex = row.parents('.cv-invitees').find('tr').index(this);
row.parents('.cv-invitees').find('tr').not(this).removeClass('selected');
row.toggleClass('selected');
}
}
}
},
200);
}
else if (iClickCounter === 2)
{
dtSecondClick = new Date();
}
else if (iClickCounter === 3)
{
if (dtSecondClick.getTime() - dtFirstClick.getTime() < 1000)
{
return;
}
iClickCounter = 0;
dbclick = true
//doubleclick functionality start.
toggleAssignBtn.addClass('is-disabled');
function moveSelectedInviteesDBClick()
{
var row = tmContainer.find("table.cv-invitees tr.selected");
if (!row.is('.assigned'))
{
var allOpenSeat = $('.cv-item .open');
var numberOpen = allOpenSeat.length;
var name = row.find("td").eq(0).text();;
var company = row.find("td").eq(1).text();
var addedInvitees = [];
allOpenSeat.each(function (index)
{
if (index < 1)
{
var openSeat = $(this);
openSeat.find('.name').text(name);
if (company != '') {
openSeat.find('.company').addClass('show').text(company);
}
var seatAssignment = new Object();
seatAssignment.company = "";
addedInvitees.push(seatAssignment);
openSeat.removeClass('open');
}
row.remove();
}
);
}
}
// moveSelectedInviteesDBClick
moveSelectedInviteesDBClick();
window.setTimeout(function ()
{
dbclick = false
}, 300);
}
}
);
} // selectInvitees end
function moveSelectedInvitees()
{
//move invitees from left to right
tmContainer.find('button.cvf-moveright').click(function ()
{
var selectedItem = $('.cv-invitees .selected');
var allOpenSeat = $('.cv-item .open');
var numberSelected = selectedItem.length;
var numberOpen = allOpenSeat.length;
var errorMsg = tmContainer.prev('.cv-alert-error');
if (numberSelected > numberOpen) {
errorMsg.removeClass('is-hidden');
}
else
{
var name;
var company;
var invitee = [];
var selectedInvitees = [];
var count = 0;
selectedItem.each(function () {
var $this = $(this);
name = $this.find("td").eq(0).text();
company = $this.find("td").eq(1).text();
invitee = [name, company];
selectedInvitees.push(invitee);
count = count + 1;
i = 0;
$this.remove();
});
var addedInvitees = [];
var items = $('div.cv-item li');
var seatItems = $('div.cv-order li');
allOpenSeat.each(function (index)
{
if (index < count)
{
var openSeat = $(this);
openSeat.find('.name').text(selectedInvitees[index][0]);
if (selectedInvitees[index][1] != '')
{
openSeat.find('.company').addClass('show').text(selectedInvitees[index][1]);
}
var seatAssignment = new Object();
seatAssignment.company = "";
addedInvitees.push(seatAssignment);
//selectedInvitees.shift();
openSeat.removeClass('open');
}
}
);
selectedInvitees = [];
}
toggleAssignBtn.addClass('is-disabled');
}
);
} // moveSelectedInvitees end
function deleteInvitees()
{
//move invitees from left to right
tmContainer.find('div.cv-tm-col-r .cv-icon-remove').click(function ()
{
//delete seat assignment
var icon = $(this);
var idx = $('.ui-sortable li').index(icon.parent());
icon.parent().fadeTo(0, 0).addClass('open').find('.name').text('Open').end().fadeTo(750, 1);
icon.parent().find('.company').removeClass('show').text('');
// icon.parent().find('.entitystub').text('00000000-0000-0000-0000-000000000000');
// icon.parent().find('.entitytype').text('0');
// icon.parent().find('.pipe').remove();
// icon.hide();
// var testSeat = $('.seat-numbers li').get(idx);
//var seatStub = j$.trim(j$(testSeat).find('.seatstub').text());
//var input = { 'seatStub': seatStub };
//AssignSeats(input, "/Subscribers/WS/SeatAssignmentService.asmx/DeleteRegistrant");
}
);
}
initTabelMgmt();
}
); // document.ready end
I guess that you interpret in your special case a double click as 3 times clicked at the same table entry. And if a user do so and if the time difference between first and second click is longer than one second, a double click will be fired. I think should be the solution to deal with this special case.
Edit 4: Please test, if it is possible to click on 3 different table column and get also double click fired. I think this is an disadvantage on how my code handles the double click. So, you need to know from which table column you have already 1 to 3 clicks set. How can we do this? Basically, there are 3 possibilities to do this:
(HTML5 only:) Make data attribute on each tr and the value for this data attribute
should be the clicks already clicke on this tr.
Define a global object key/value pair object, which holds the
event-ID (but I don´t know how to get this back by jQuery driven
events) as the key and the amount of clicks already done as the
value. And then if you are on the next click, you can decide what is
to do now for this tr. This is my favorite alternative!
Last but not least: Only register the click event on every tr and
make for each click-registering an own global area, so that we just
avoid the actual problem. You can do this e. g. by making an JS
Object which hold a member variable as the iclickCounter and you
make a new object of this class, each time a new click event is
registered. But this alternative need a lot more code and is main-memory-hungry.
All of thes possible options need a wrap around your click event, e. g. a loop, that iterates over all tr elements in the given table. You did this already partially by calling the jQuery-function .find(..). This executes the closure on every found html element. So, in your case on all tr elements in the searched table. But what you need to do is to make the workaround of one of my options given above.
I'm looking for way to use local storage to remember the CSS settings of a expand/collapse element
so for my JavaScript looks like this (which grabs the id and handles the expand/collapse)
function toggleHeight(id, link) {
var e = document.getElementById(id);
if(e.style.maxHeight == '450px') {
e.style.maxHeight = '0px';
} else {
e.style.maxHeight = '450px';
}
}
So what I am looking for is something that grabs the div id på clicking a link and stores the changes when clicking and then remembering is when refreshing.
Maybe something like this
var height = localStorage.getItem(id+"-height");
localStorage.setItem(id+"-height", height);
As promised here is my solution:
<script type="text/javascript">
function toggleHeight(id, link) {
var e = document.getElementById(id);
var height = localStorage.getItem(id);
if(e.style.maxHeight == '450px' || e.style.maxHeight == 'inherit') {
e.style.maxHeight = '0px';
localStorage.setItem(id,"closed");
} else {
e.style.maxHeight = '450px';
localStorage.setItem(id, "open");
}
}
function load() {
var setting
var e
var link
for (x in localStorage){
setting = localStorage.getItem(x);
e = document.getElementById(x);
link = document.getElementById('forumlink'+x);
if (setting == 'open')
{
e.style.maxHeight = '450px';
}
else
{
e.style.maxHeight = '0px';
}
}
}
</script>
This stores the state of the div when clicked and sets in to open/closed
On page load it grabs the stored value and sets the max-height css after the open/closed value..
Hope some others can make use of this
This is how I solved it: working fiddle
//extra methods to get and set objects in staid of strings
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
//fetch the object or make a new and set constant values
var toggleState = localStorage.getObject('toggleState') || {},
MIN_SIZE= '0px',
MAX_SIZE= '450px';
//shown is an optional parameter
function toggleHeight(id, shown) {
var e = document.getElementById(id);
if(shown === true || (typeof shown === "undefined" && e.style.maxHeight == MIN_SIZE)) {
show(id);
} else {
hide(id);
}
}
function show(id){
var e = document.getElementById(id);
e.style.maxHeight = MAX_SIZE;
toggleState[id] = true;
localStorage.setObject('toggleState',toggleState);
}
function hide(id){
var e = document.getElementById(id);
e.style.maxHeight = MIN_SIZE;
toggleState[id] = false;
localStorage.setObject('toggleState',toggleState);
}
//loop over it to set initial values
for(var i in toggleState){
toggleHeight(i, toggleState[i]);
}
//do manual toggle, hide, show
toggleHeight('someID');
You see I separated the show and hide so you can show hide them individually too, if you want or you can still use the toggle method.