JS accordion area-expanded One section at a time - javascript

I'm using this example for the accordion and trying to play with it to have just One Section Open at a time
I know how to create this using iQuery, but here I'm puzzled. Should I also do something like forEach or !this or to specify current?
class Accordion {
constructor(domNode) {
this.rootEl = domNode;
this.buttonEl = this.rootEl.querySelector('button[aria-expanded]');
const controlsId = this.buttonEl.getAttribute('aria-controls');
this.contentEl = document.getElementById(controlsId);
this.open = this.buttonEl.getAttribute('aria-expanded') === 'true';
// add event listeners
this.buttonEl.addEventListener('click', this.onButtonClick.bind(this));
}
onButtonClick() {
this.toggle(!this.open);
}
toggle(open) {
// don't do anything if the open state doesn't change
if (open === this.open) {
return;
}
// update the internal state
this.open = open;
// handle DOM updates
this.buttonEl.setAttribute('aria-expanded', `${open}`);
if (open) {
this.contentEl.removeAttribute('hidden');
} else {
this.contentEl.setAttribute('hidden', '');
}
}
// Add public open and close methods for convenience
open() {
this.toggle(true);
}
close() {
this.toggle(false);
}
}
// init accordions
const accordions = document.querySelectorAll('.accordion h3');
accordions.forEach((accordionEl) => {
new Accordion(accordionEl);
});

Related

'if' statement and eventListener question

I'm building a website and right now I'm having an issue trying to get an if statement to read a change of state variable.
I'm trying to close my navbar menu when I click anywhere in the body, other than the navbar. However, my if statement that contains the event listener for the body will not execute because (I think) that the change of state variable that is being used for the condition (true when menu is open, false when menu is closed) is just not being read.
When I open the nav menu, the change of state variable changes to true, as it is intended to. When I close the menu using the button on the nav bar, the change of state variable changes to false, as it is intended to.
Here's my code:
"use strict";
const btnNav = document.querySelector(".nav-btn--container");
const linkContainer = document.querySelector(".link-container");
const header = document.querySelector(".header");
const sidebar = document.querySelector(".sidebar");
const bodyChildren = header.parentElement.children;
const navBtn = document.querySelector(".nav-btn");
const menu = document.querySelector(".sidebar__menu");
const body = document.querySelector(".container");
/**** change of state variables ****/
let menuIsOpen = false;
/**** functions ****/
const closeMenu = function () {
addRemoveBlur("remove");
navBtn.classList.remove("nav-btn--opened");
sidebar.classList.remove("blur");
navBtn.classList.add("nav-btn--closed");
menu.style.visibility = "hidden";
menu.style.transform = "translateX(-150%)";
menuIsOpen = false;
};
const openMenu = function () {
addRemoveBlur("add");
navBtn.classList.remove("nav-btn--closed");
navBtn.classList.add("nav-btn--opened");
menu.style.visibility = "visible";
menu.style.transform = "translateX(0%)";
menuIsOpen = true;
};
const closeMenuByBody = function (e) {
const click = e.target;
closeMenu();
};
const openCloseMenu = function () {
if (!menuIsOpen) {
openMenu();
return;
}
if (menuIsOpen) {
closeMenu();
return;
}
};
/**** this is the problem ****/
if (menuIsOpen) {
body.addEventListener("click", function (e) {
closeMenuByBody(e);
});
}
The problem is that the event listener is never initialized, as your menuIsOpen variable is always declared false.
You should switch your if statement to be contained within the click event handler, like so:
body.addEventListener("click", function (e) {
if (menuIsOpen) {
closeMenuByBody(e);
}
});
You should also consider the following changes to your openCloseMenu method (here renamed to toggleMenu):
const toggleMenu = function () {
if (menuIsOpen) {
closeMenu();
} else {
openMenu();
}
};
As you are evaluating a boolean value, there is no need to test it in two different if expressions: you check if it's true and do something if it is, or else you do something knowing that it's false.
You could also remove your closeMenuByBody method, and just call the closeMenu method from your event listener, as you aren't doing anything in it appart from that:
body.addEventListener("click", function (e) {
if (menuIsOpen) {
e.preventDefault();
closeMenu();
}
});

Remove a JavaScript class method from eventlistener inside another method of the same class

Description & Goal
I have a list with items and clicking on an item shows a detail view, shows a close button and add the eventlistener for closing this item to the button.
By clicking on this button the detail view should be closed and the eventlistener should be removed.
I can't use an anonymous function because removing won't work with it (See here and here).
Problem
Removing doesn't work.
Code
export default class ToggleDetails {
constructor(jobAdId) {
this.jobAdId = jobAdId
this.opened = false
}
toggle() {
const jobAdContainer = document.getElementById(this.jobAdId)
// doing some other css manipulation for the detail view
this.handleCloseButton()
}
handleCloseButton() {
const closeButton = document.getElementById('uh-job-detail-close-button')
const $this = () => {
this.toggle()
}
if (this.opened === true) {
closeButton.classList.remove('uh-job-detail-close-button-show')
closeButton.removeEventListener('click', $this)
this.opened = false
} else {
closeButton.classList.add('uh-job-detail-close-button-show')
closeButton.addEventListener('click', $this)
this.opened = true
}
}
}
HTML structure
"Solution"/Workaround
I solved it, by cloning and replacing the button with itself. The clone doesn't have the eventlisteners (Thanks to this post)
handleCloseButton () {
const closeButton = document.getElementById(
'uh-job-detail-close-button')
closeButton.classList.toggle('uh-job-detail-close-button-show')
if (this.opened === true) {
const elClone = closeButton.cloneNode(true)
closeButton.parentNode.replaceChild(elClone, closeButton)
this.opened = !this.opened
} else {
closeButton.addEventListener('click',
() => { this.toggle() })
this.opened = !this.opened
}
}
Try using a named function and passing the value of this into toggle:
export default class ToggleDetails {
constructor(jobAdId) {
this.jobAdId = jobAdId
this.opened = false
}
toggle(t) {
// doing some other css manipulation for the detail view
t.handleCloseButton()
}
handleCloseButton() {
const closeButton = document.getElementById('uh-job-detail-close-button')
let listenerToggle = () => {
this.toggle(this);
};
if (this.opened === true) {
closeButton.classList.remove('uh-job-detail-close-button-show')
closeButton.removeEventListener('click', listenerToggle)
this.opened = false
} else {
closeButton.classList.add('uh-job-detail-close-button-show')
closeButton.addEventListener('click', listenerToggle)
this.opened = true
}
}
}

Contextual Menu issue in office-fabric-ui on second click

We are working on Office UI Fabric JS 1.2.0. Issue is with context menu having submenu items. When you open Second level, and then click anywhere on menu, first level menu was closing and second menu was re-aligning to Top-Left of page. We couldn't find the solution in next version of fabric also.
The issue gets resolved after overriding two methods from fabric.js of ContextualHost as follows:
fabric.ContextualHost.prototype.disposeModal = function () {
if (fabric.ContextualHost.hosts.length > 0) {
window.removeEventListener("resize", this._resizeAction, false);
document.removeEventListener("click", this._dismissAction, true);
document.removeEventListener("keyup", this._handleKeyUpDismiss, true);
this._container.parentNode.removeChild(this._container);
if (this._disposalCallback) {
this._disposalCallback();
}
// Dispose of all ContextualHosts
var index = fabric.ContextualHost.hosts.indexOf(this);
fabric.ContextualHost.hosts.splice(index, 1);
//Following is original code removed
//var i = ContextualHost.hosts.length;
//while (i--) {
// ContextualHost.hosts[i].disposeModal();
// ContextualHost.hosts.splice(i, 1);
//}
}
};
fabric.ContextualHost.prototype._dismissAction = function (e) {
var i = fabric.ContextualHost.hosts.length;
while (i--) { //New added
var currentHost = fabric.ContextualHost.hosts[i];
if (!currentHost._container.contains(e.target) && e.target !== this._container) {
if (currentHost._children !== undefined) {
var isChild_1 = false;
currentHost._children.map(function (child) {
if (child !== undefined) {
isChild_1 = child.contains(e.target);
}
});
if (!isChild_1) {
currentHost.disposeModal();
}
}
else {
currentHost.disposeModal();
}
}
}
};
Hope this question + answer helps someone looking to override fabric.js original code.

jquery draggable revert programmatically

I am currently developing a calendar where activities can be drag&dropped to other days.
When an activity is dropped into a different day, I show a custom modal using durandal's dialog plugin. The problem is when an user closes the modal, the activity has to revert to its original position. When an activity is dropped the following code is called:
function showDroppedActivityModal(obj) {
require(['modals/droppedActivityModal/droppedActivityModal', 'moment'], function(droppedActivityModal, moment) {
droppedActivityModal.show(obj).then(function(response) {
if(response !== false) {
...
}
// dialog closes
else {
calendarView.revertActivity.notify({ revert: true})
}
});
});
}
In my calendarView I implemented the revertActivity event to set revert to true but the function never re-evaluates itself but i'm able to receive the new revert value (true).
$(activity).draggable({
revert: function() {
var revert = false;
self.revertActivity.attach(function(sender, args) {
revert = args.revert;
});
return revert;
}
});
Custom event code:
function CalendarEvent(sender) {
this._sender = sender;
this._listeners = [];
}
CalendarEvent.prototype = {
attach : function (listener) {
this._listeners.push(listener);
},
notify : function (args) {
var index;
for (index = 0; index < this._listeners.length; index += 1) {
this._listeners[index](this._sender, args);
}
},
remove : function (listener){
this._listeners.remove(listener);
}
};
this.revertActivity = new CalendarEvent(this);

Making a method in a plugin accessible globally?

Given the jQuery dropdown plugin below. Is there a way to add a method that would allow for a separate function outside of the dropdown to 'hideMenu'? Thanks
For example, if I applied the plugin to a div with an ID like so:
$('#settings.dropdown').dropDownMenu();
How could I then call to close the dropDownMenu w hideMenu from outside of the plugin? Thanks
jQuery.fn.dropDownMenu = function() {
// Apply the Dropdown
return this.each(function() {
var dropdown = $(this),
menu = dropdown.next('div.dropdown-menu'),
parent = dropdown.parent();
// For keeping track of what's "open"
var activeClass = 'dropdown-active',
showingDropdown = false,
showingMenu,
showingParent,
opening;
// Dropdown Click to Open
dropdown.click(function(e) {
opening = true; // Track opening so that the body click doesn't close. This allows other js views to bind to the click
e.preventDefault();
if (showingDropdown) {
dropdown.removeClass(activeClass);
parent.removeClass(activeClass);
showingMenu.hide();
showingDropdown = false;
} else {
showingDropdown = true;
showingMenu = menu;
showingParent = parent;
menu.show();
dropdown.addClass(activeClass);
parent.addClass(activeClass);
}
});
// When you click anywhere on the page, we detect if we need to blur the Dropdown Menu
$('body').click(function(e) {
if (!opening && showingParent) {
var parentElement = showingParent[0];
if (!$.contains(parentElement, e.target) || !parentElement == e.target) {
hideMenu();
}
}
opening = false;
});
// hides the current menu
var hideMenu = function() {
if(showingDropdown) {
showingDropdown = false;
dropdown.removeClass(activeClass);
parent.removeClass(activeClass);
showingMenu.hide();
}
};
});
};
jQuery advises making multiple methods available through the plugin itself:
jQuery.fn.dropDownMenu = function(method) {
var methods = {
init: function() {
// Put all your init code here
},
hide: function() {
hideMenu();
}
};
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
function hideMenu() {
// ...
}
};
See http://docs.jquery.com/Plugins/Authoring#Plugin_Methods
Update: Use like this:
// Use the plugin normally to run the init method
$('#settings.dropdown').dropDownMenu();
// Call the hide method
$('#settings.dropdown').dropDownMenu('hide');
Sure. Give hideMenu to the global window object, like this:
window["hideMenu"] = function() {
if(showingDropdown) {
showingDropdown = false;
dropdown.removeClass(activeClass);
parent.removeClass(activeClass);
showingMenu.hide();
}
};
You can then call it as usual anywhere you need to.

Categories