Giter Site home page Giter Site logo

twikito / easy-toggle-state Goto Github PK

View Code? Open in Web Editor NEW
280.0 8.0 33.0 7.85 MB

A tiny JavaScript library to easily toggle the state of any HTML element in any contexts, and create UI components in no time.

Home Page: https://twikito.github.io/easy-toggle-state/

License: MIT License

JavaScript 100.00%
toggle switch dropdown tooltip trigger-element navigation-buttons lightboxes tabs checkbox radio

easy-toggle-state's Introduction

Easy Toggle State

A tiny JavaScript library to easily toggle the state of any HTML element in any contexts, and create UI components in no time.

Dropdown, navigation button, tooltip, collapsible panel, lightbox, tabs, switches… UI components made in minutes without worried about JavaScript. Only set a few HTML attributes, and code the rest with your CSS skills.

See some examples in the documentation.

Status

GitHub release (latest by date) npm Cdnjs npm bundle size npm bundle size

David David

Why?

A front-end developer often has to code scripts for interface components. Components such as drop-downs, navigation buttons, tooltips, expandable panels, lightboxes, tabs, etc.

The thing is… Most of these components expose a recurrent behavior: a trigger element toggles the state of one or more target elements. So why not code this behavior once and for all?

So here is a solution: a simple script to toggle the state of a trigger element with a CSS class. You can then associate this element with one or more others: let's call them targets. By adding the right HTML attributes, it can adapt to any contexts and behave like a chosen component.

Only focus on adjusting the rest with your CSS creativity.

Quick start

Several quick start options are available:

Documentation

Easy Toggle State's full documentation is hosted on GitHub Pages at twikito.github.io/easy-toggle-state/.

Contribution

License

MIT. Copyright (c) Matthieu Bué

easy-toggle-state's People

Contributors

borisschapira avatar dependabot-preview[bot] avatar dhoko avatar greenkeeper[bot] avatar twikito avatar vdsabev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easy-toggle-state's Issues

Triggers don't work when loaded via XHR

I have two buttons: "login" and "register"
They trigger a "loginModal" and "registerModal".
Inside these modals there are links to close the current open modal and open the other one. (Switch between them)

<a href="#" data-toggle-class-on-target="hidden"
            data-toggle-target="#registerModal"
            data-toggle-trigger-off="#loginModal"
            data-toggle-modal data-toggle-escape>
    Need an account? Register
</a>

<a href="#" data-toggle-class-on-target="hidden"
            data-toggle-target="#loginModal"
            data-toggle-trigger-off="#registerModal"
            data-toggle-modal data-toggle-escape>
    Already registered? Login
</a>

This works when its all in a single hardcoded html file. However, when I load the modal content (and the above links) with XHR, this doesn't work anymore.

Am I doing it wrong? Or is this a bug? Or is that generally not supported?

Error in IE11 and IE10

Hi,

I have stumbled upon an error in Internet Explorer 11 and 10.
I thought at first that it was coming from me, but it seems that you have the same error on the demo site.

SCRIPT1002: Syntax error in easy-toggle-state.es6.min.js

IE is reporting this line in error:

/* Retrieve a valid HTML attribute. */
const dataset = (key => ["data", PREFIX, key].filter(Boolean).join("-"));

Codepen example for simple tabs doesn't work

Describe the bug
In the documentation, the Codepen example associated to simple tabs doesn't work as expected.

To Reproduce
Steps to reproduce the behavior:

  1. Follow the codepen link in the documentation for simple tabs
  2. See error

Expected behavior
The expected behavior is the one described in documentation.

Screenshots
image
image
image

Desktop (please complete the following information):

  • OS: macOS Monterey 12.4
  • Browser: Safari
  • Version: 15.5

Additional context
None.

Programmically fire toggle, open and close on element

When making things I noticed a missing feature.

Let's say I have a chain of events and after they are done I need to open, close or toggle a special element. In this case the toggle is not made by user interaction, but by the application itself.

What I miss is these functions:

EasyToggleStateTrigger('open', element);
EasyToggleStateTrigger('close', element);
EasyToggleStateTrigger('toggle', element);

or

openEasyToggleState(element);
closeEasyToggleState(element);
toggleEasyToggleState(element);

but I prefer the first one better. What do you think?

data-toggle-group with data-toggle-outside does not work

Overall, this lib works great. However I could not get it work with data-toggle-outside. Does it work with data-toggle-group?

My code

I've shorten it down a bit to only include the important parts.

<li data-toggle-class="active" data-toggle-target="widget-create-file" data-toggle-group="tabsGroup" data-toggle-outside>
</li>
<li data-toggle-class="active" data-toggle-target="widget-create-folder" data-toggle-group="tabsGroup" data-toggle-outside>
</li>

<widget-create-file>
</widget-create-file>

<widget-create-folder>
</widget-create-folder>

What I want is that when I click outside of both my buttons and my targets, my targets should hide no matter what the current state is.

I use Google Chrome latest on Windows.

I also tried a few other crazy things that did not work, like this:

<body data-toggle-trigger-off data-toggle-group="tabsGroup">

Any ideas?

I could do it with javascript, but it would be nice to be able to pull it off with this lib.

Allow multiple triggers to modify a single toggle-able node

Is your feature request related to a problem? Please describe.
Allowing multiple triggers to interact with the same toggle-able element would be very welcome. For example, a main navigation trigger/button might toggle a modal or 'sidebar' into view. Being able to click on a body link/button trigger to open the same 'sidebar' would allow users the flexibility of which trigger to use to access the modal.

Describe the solution you'd like
Something like ...

<header>
    <button data-toggle-class data-toggle-target=".modal">Open Modal</button>
</header>

<main>
<p><button data-toggle-class data-toggle-target=".modal">This also triggers</button> the modal, but if the modal is already active, it would close the modal instead.</p>
</main>

<!-- is-active from any trigger that targets it -->
<nav class="modal"></nav>

Note: This would also need to work with radio group based triggers. (This is the specific use case I need)

I don't have the time to put together a reduced test case at the minute, but would like to when I have time. This is a great library, and I'd love to see it improve further to solve more edge cases.

Allowing mutliple classes within toggle-class

Sorry if I missed this, as its not currently mentioned in the docs.

I'd like to be able to split class concerns, i.e is-active and is-animating. This allows us to use the toggle in different ways. i .e having normal behaviour on a component with is-active, and then applying is-animated to separate components that need it.

Something like:

<button class="c-btn" data-toggle-class="is-active, is-animated" data-toggle-target="[data-component]">Button</button>

<div class="component" data-component>...</div>

Feedback

As requested on Twitter. I’m opening an issue because Twitter is too painful for long form text.

My thoughts as I peruse the site, in no particular order:

  • Nice design, green on white is too low contrast though
  • Premise sounds nice, but takes WAY too long to get to the meat and show a demo or something. Lots of info about how to install before I even know if I'm interested.
  • Why do I need to run JS for a purely HTML API? This excludes a bunch of designers who aren't comfortable with JS. Just make the attributes work, automatically, at least for the bundle version. Use Mutation Observers to pick up new ones too. Provide manual control for people with demanding use cases.
  • Even the "how to use" section drills down into the nitty gritty of before it convinces me I need this. Not only that, but it tells me what I shouldn't do, before it tells me what I should do! And tells me off about something I haven't even done. WAT?
  • The entire documentation suffers from the curse of knowledge. You know what this does and why it's useful, so there is almost nothing about that. There is no tutorial, no description of the main concepts, only reference-style documentation, which is useful for non-beginners. Even the examples in the docs are essentially foo/bar type examples, not real use cases. What can I make with this?? It would be good to have small demos to illustrate how each attribute works and why it's useful. Or even link to a demo that uses it.
  • I'm now in the "Advanced" section. I do not understand what the headings are. Are they attributes? Oh, I see, they are attributes, some have values. What is a group? What is a radio group? Is it the name of the radios?
    I'm even more puzzled about how these work or why would I need them.
  • Typo: "and every attributes" --> "and other attributes". I'd suggest allowing users to customize the prefix including the data- part.
  • I'm not sure how data-toggle-trigger-off works. "Add this attribute to an element inside a target to enable it to toggle the state of this target. For example, a close button inside a modal." — Show, don't tell! Include a demo!
  • I do not understand the "Toggling combination" section at all. Neither what problem it's solving, nor how it's solving it.
  • I finally got to the demos!!! After everything else! Definitely move this section WAY up.
  • Switchbox eample: aria-hidden is not changed according to which label is visible. Is this something ETS can do? If not, why? If so, this would be a good way to showcase it.
  • How is the tooltip example better than CSS? It looks like aria-hidden is toggled here. How does that work? Some text about this would be useful.
  • Idea: Make ETS attributes clickable in demos, to take you to the reference for each attribute.
  • All of these demos are very component-y. It would be nice to provide some declarative HTML syntax to turn them into a web component without writing JS!
  • Dropdown doesn't appear to work. I can't select anything. (Chrome OSX v86)
  • "Even if you want to use X in some case you can't" is incorrect grammar. It's "cases".
  • The SVG focusable attribute is not implemented in most browsers.

Comments on attribute API

  • data-toggle-escape is a bit too constrained. What about data-toggle-key="Escape"? You just use evt.key in your JS, no need to have a dictionary of all possible key names.
  • Same with data-toggle-arrows, e.g. what if you want other keys for navigation or only horizontal/vertical arrows? Maybe data-toggle-navigation="arrows" or data-toggle-navigation="horizontal arrows" or data-toggle-navigation="vertical arrows" (also offers an extension point for other keys in the future).
  • What happens if conflicting triggers are specified? E.g. data-toggle-event is mouseover and data-toggle-escape is specified?
  • It would be nice if there was a way to make data-toggle-target relative to the current element, to avoid having to generate ids for repeated elements. Perhaps by the selector using & or :scope to represent the current element?
  • It might be good for data-toggle-target-next to optionally accept a value to define what the "next" element is, when it's not the next sibling.
  • What happens if I just data-toggle-class by itself? Might be a good default to assume the target is the current element itself. Wait, this is how it works, based on the checkbox element. Something to document then!

Overall, I think this is a nice library that could be useful for developing a variety of interactions without writing JS, but the documentation needs a lot of work to be user-friendly.

Toggles that target elements with data-toggle-trigger-off in them hijack focus on data-toggle-escape/data-toggle-outside

Thank you for your response to my previous bug report, while I was working with the library some more I came across another data-toggle-trigger-off bug

Describe the bug
When an element receives a data-toggle-target that contains an element with data-toggle-trigger-off, and that toggle is opened and then escaped or closed via data-toggle-escape and/or data-toggle-outside. If focus had been moved to elsewhere on the page, the focus is moved back to the toggle element instead of remaining where it is on the page. This does not occur with elements that have a data-toggle-target without a data-toggle-trigger-off element in the target element

To Reproduce
https://codepen.io/suitemel/pen/JjBbWKW
Here is a codepen with the issue reproduced

Expected behavior
Focus shouldn't be moved back to the element once it's closed, focus should remain where it is

Desktop (please complete the following information):

  • OS: macOS Big Sur v 11.7.1
  • Browser: Chrome
  • Version 108.0.5359.124

Additional context
I've been using your library extensively for an ADA compliant site (data-toggle-trigger-off being used specifically for navigation menus) and due to this issue I've ran into I've had to create my own version of the data-toggle-trigger-off in my code to have the toggle get closed and avoid having focus get moved unnecessarily.

Possible to work on hover?

Love this little script.

Is it possible to make work on hover or is it always a click event?

Thank you 👍

Form inside modal/dialog, cannot tab into?

I have a form within a dialog popup, all tabbing working fine apart from when a form appears within the popup, is this a form issue or something i can tweak with easy-toggle?

The form tabs fine through the input fields when not in dialog popup.

Browser support

Suggest listing supported browsers in the documentation page.

Mobile Specific Control?

Is it possible to have screen size control of the toggle?

For example you have a mobile drop down menu you toggle on and off however, when you re-size the browser window it would still be there because the button you used to turn it on/off is also mobile specific?

So once you made the screen a certain size it would toggle off if it was active?

Using data-toggle-outside with a trigger containing another tag

Hello! First of all, thank you for this amazing library, great job!

I'm trying to implement a tooltip that would open after clicking a button with an img tag inside of it:

HTML

<button data-toggle-class-on-target="hidden" data-toggle-target=".tooltip" data-toggle-event="click" data-toggle-outside>
  <img src="https://secure.gravatar.com/avatar/37640f3902ef08c7fad7d306c912ebf0?d=identicon&s=200">
</button>
<span class="tooltip hidden">Awesome tooltip</span>

CSS

.hidden {
  display: none !important;
}

.tooltip {
  background-color: #00b074;
  color: white;
}

button {
  cursor: pointer;
  border: none;
  margin: 0;
  padding: 0;
  width: auto;
  overflow: visible;
  background: transparent;
  color: inherit;
  font: inherit;
  line-height: normal;
  outline: none;
}

img {
  border-radius: 50%;
  width: 100px;
  height: 100px;
}

https://codepen.io/lukaszwnek/pen/pobVZQo

However, clicking the button doesn't seem to show the tooltip. It starts working when I either:

  1. remove the data-toggle-outside attribute from the button (which I don't want to do since I need that to close it).
  2. moving all the data-toggle attributes to the img (but this goes against your own recommendation to use buttons as triggers).

The issue isn't limited to the img tag, from what I've seen it persists with any tag inside of the button (only plain text works).

It feels like a bug, but maybe there's something wrong with my setup? I'd really appreciate your opinion @Twikito.

Thanks!

Multiple Targets?

Is it possible to target multiple classes, or is that not the point, elements always have to be adjacent?

For example.

<button class="hero-menu-button main-btn" type="button" data-toggle-class data-toggle-escape data-toggle-target=".navigation-panel" data-toggle-target-self=".hero-menu-button">

Only thing that happens is is-active is added to the div .navigation-panel when i needed it adding to the actual button as well?

Many thanks.

Double click to open, single click to outside blur

I've changed the dropdown example and added an event. In this case I double click to open the dropdown, so far so good. When I click outside nothing happends because I need to double click outside to make it hide again.

In my case I want to double click to open and single click to hide. Is that possible or do I need to roll out an own solution? Or a hook for it?

https://twikito.github.io/easy-toggle-state/#dropdown

<div class="example-dropdown">
	<button type="button"
		class="example-dropdown-button"
		data-toggle-class="is-open"
		data-toggle-target-next
                data-toggle-event="dblclick"
		data-toggle-outside
		data-toggle-escape>
		Select something here
	</button>
	<ul class="example-dropdown-list">
		<li>
			<button type="button">Lorem ipsum dolor</button>
		</li>
		<!-- Several options -->
	</ul>
</div>

Feature

A possible feature would be data-toggle-outside-event to specify a special event for outside clicks.

Hack it

For anyone else having this issue, it's possible to fix it by hacking the code like this:

Go here:

https://github.com/Twikito/easy-toggle-state/blob/master/dist/easy-toggle-state.es6.js#L188

Change it to:

if (target.hasAttribute(OUTSIDE) && target.isToggleActive) {
  document.addEventListener("click", documentEventHandler, false);
}

JavaScript Event hooks

Is there any way to expose before, after, on event hooks? I'm trying to avoid animating max-height and animate an explicit height that is set by JavaScript.

Warning in console log if no data-toggle-class is found

When using Ajax, which means I get the results later I get this on init:

Easy Toggle State is not used: there's no trigger with 'data-toggle-class' attribute to initialize.

While the information is correct, I'm well aware of this, because I trigger the function window.initEasyToggleState(); at a later point in time.

So I guess this is a question. Is this warning really needed? To me it's kind of bloating my console log.

Tabs only 1 Tabs active

Is there a Problem with the Tab toggle attr. ? i have a Setup like this

<div class="u-col-16">
  <div class="TabContainer-panel" 
        id="tabContainer1"
	role="tabpanel"
	aria-labelledby="tabContainer1"
	aria-hidden="false">
    <img/>
</div>
  <div class="TabContainer-panel" 
        id="tabContainer1"
	role="tabpanel"
	aria-labelledby="tabContainer2"
	aria-hidden="true">
    <img/>
</div></div>
<div class="u-col-16">
    <button type="button"
	data-toggle-class
	data-toggle-target="#tabContainer1"
	data-toggle-radio-group="tabsGroup"
	data-toggle-is-active
	role="tab"
	aria-selected="true"
	aria-controls="tabContainer1">
          button1
     </button>
    <button type="button"
	data-toggle-class
	data-toggle-target="#tabContainer2"
	data-toggle-radio-group="tabsGroup"
	data-toggle-is-active
	role="tab"
	aria-selected="true"
	aria-controls="tabContainer2">
          button1
     </button>
</div>

He renders the is-active class into the div container but i can always activate both tabs at the same time. So in this example both image are among themselves. I want that they replace each other.

The CodePen example doesn't work good as well.

Thanks for some feedback

Chris

Unbind or destroy an instance?

Is there a way to unbind/destroy and reinit an easy-toggle instance? My scenario is that I want to use easy toggle on an element on mobile, but not on desktop. I was thinking in my JS on screen resize I could destroy or reinit the instance depending on the screen size.

Some features

If an "outside trigger" has been added to a trigger, a feature must be added to exclude it from its own children.


I explained it at length below. But let me describe it briefly, if we make a click, if it corresponds to an element inside the element, it will never activate its status, since it accepts it as a double click or trigger then external click.

with data-toggle-outside

<section>
    <div id="el-1" data-toggle-class="active" data-toggle-outside>
        CLICK ME   ------------------------------> Scenario 1
        <p>CLICK ME</p>   ---------------> Scenario 2
    </div>
    <span>OUTSIDE CLICK ME</span> --> Scenario 3
<section>

Scenario 1

#el-1 active.

Scenario 2

#el-1 as soon as it becomes active it becomes passive immediately.
Because considers to be an outside element it.

Scenario 1 + Scenario 2

#el-1 Active in first click, passive in second click
Nothing is wrong here, because when scenario 1 is repeated twice, the same thing will happen.

Scenario 1 + Scenario 3

#el-1 Active in first click, passive in second click
Nothing is wrong here, because <span> is an outside element.

with data-toggle-outside-parents

<section>
    <div id="el-1" data-toggle-class="active" data-toggle-outside-parents>
        CLICK ME   ------------------------------> Scenario 1
        <p>CLICK ME</p>   ---------------> Scenario 2
    </div>
    <span>OUTSIDE CLICK ME</span> --> Scenario 3
<section>

Scenario 1

#el-1 active.

Scenario 2

#el-1 active.

Scenario 1 + Scenario 2

#el-1 Active in first click, passive in second click.

Scenario 1 + Scenario 3

#el-1 Active in first click, passive in second click.

Toggle tabs from a select box

Hello! Is there a way to do something like this:

<select>
    <option value="1" data-toggle-target="#tab1" data-toggle-radio-group="tabsGroup">Option 1</option>
    <option value="2" data-toggle-target="#tab2" data-toggle-radio-group="tabsGroup">Option 2</option>
    <option value="3" data-toggle-target="#tab3" data-toggle-radio-group="tabsGroup">Option 3</option>
</select>

<div id="tab1">Panel 1</div>
<div id="tab2">Panel 2</div>
<div id="tab3">Panel 3</div>

Bug with data-toggle-class-on-target

  1. When loading tabs everything works as expected on load.
  2. When clicking the second tab, all classes are removed from the first target. Exepected behaviour is to use data-toggle-class-on-taget which in my case is to toggle flex hidden. In this case it means, remove flex and keep hidden, not remove all classes.
  3. When clicking around on the other tabs it works as expected.

My guess is that something unexpected happends when data-toggle-is-active is used on a tab. If I move that class to the second tab it causes the same problem, but for the second tab.

Code

Fiddle

https://jsfiddle.net/fzty12we/

HTML

<div class="example-tabs">
	<button type="button"
    data-toggle-class-on-trigger="bg-red-500 text-white"
    data-toggle-class-on-target="flex hidden"
		data-toggle-target="#tabPanel_1"
		data-toggle-radio-group="tabsGroup"
		data-toggle-is-active>
		tab 1
	</button>
	<button type="button"
    data-toggle-class-on-trigger="bg-red-500 text-white"
    data-toggle-class-on-target="flex hidden"
		data-toggle-target="#tabPanel_2"
		data-toggle-radio-group="tabsGroup">
		tab 2
	</button>
	<button type="button"
    data-toggle-class-on-trigger="bg-red-500 text-white"
    data-toggle-class-on-target="flex hidden"
		data-toggle-target="#tabPanel_3"
		data-toggle-radio-group="tabsGroup">
		tab 3
	</button>
</div>
<div class="hidden" id="tabPanel_1">
	Panel 1<br>
	Lorem ipsum dolor sit amet…
</div>
<div class="hidden" id="tabPanel_2">
	Panel 2<br>
	In in erat blandit ante mollis tincidunt…
</div>
<div class="hidden" id="tabPanel_3">
	Panel 3<br>
	Nam posuere tortor a augue vulputate…
</div>

CSS

.bg-red-500 {
  background: red;
}

.text-white {
  color: white;
}

.hidden {
  display: none;
}

.flex {
  display: flex;
}

Add a default state attribute for target elements

Is your feature request related to a problem? Please describe.
I'm always frustrated when I need to wait the initialization of the triggers to have the default state of the target elements. This behavior creates some glitchs or layout shifting which provides a bad user experience.

Describe the solution you'd like
Can it be possible to have an attribute like data-toggle-is-active (eg: data-toggle-target-is-active) for the target elements to avoid waiting initialization to have the default state for target elements ?

Describe alternatives you've considered
None.

Additional context
None.

Can't initialize script

The console reads on page load:
"Easy Toggle State is not used: there's no trigger to initialize."

I have attempted to follow the steps described in the examples here.

html:

<button type="button"
	class="example-checkbox"
	data-toggle-class="is-checked">
</button>

css:

.example-checkbox {
	display: inline-block;
	width: 1em;
	height: 1em;
	padding: 0;
	box-sizing: content-box;
	border: 2px solid darkgrey;
	outline: none;
	border-radius: .25em;
	background-color: white;
	text-align: center;
	line-height: 1;
	cursor: pointer;
	transition: .15s ease-out;
}
.example-checkbox:hover,
.example-checkbox:focus {
}
.example-checkbox::before {
	display: block;
	opacity: 0;
	content: "✔";
	transition: opacity .15s ease-out;
}
.example-checkbox.is-checked::before {
	opacity: 1;
}

/* For internal label */
.example-checkbox-container {
	padding: 0;
	border: none;
	outline: none;
	background: none;
}

I have attempted all examples with the same result. easy-toggle-state never seems to initialize.
I have installed via npm, and have it linked at the end of my page.

The application in use is a single page application which dynamically loads html snippets from a cms backend. I'm assuming the issue here is that the rendered content is inserted into the DOM fractionally slower than the layout executes the easy-toggle-state script, and because the script is called only once at page load, it isn't responding to the changing content.

Any advice?

Can you target multiple elements?

Is your feature request related to a problem? Please describe.
I'd love to be able to target both the <html> and an <div> element, so that I can manipulate both nodes.

Describe the solution you'd like
When I click a trigger, I would like to add a class on the <html> element, and on the <div> element.
For eg. modal--is-active class. This means I can trigger overflow hidden on the html to stop the viewport moving, whilst also activating the modal as well.

Describe alternatives you've considered
I don't think this is possible yet.

data-toggle-trigger-off elements do not unbind

Describe the bug
Having created a mobile menu toggle with the unbind action being called from mobile to desktop. I noticed that if an element has data-toggle-trigger-off it does not unbind with the rest of the unbound elements

To Reproduce
https://codepen.io/suitemel/pen/xxJEWwK
Here is a codepen with the issue reproduced

Expected behavior
I expect the data-toggle-trigger-off elements to be unbound as well

Desktop (please complete the following information):

  • OS: macOS Big Sur v 11.7.1
  • Browser: Chrome
  • Version 108.0.5359.124

Clicking on a child element closes toggle

Hey there,

First off, love this little plugin/script. Such a huge time saver :)

I've added a toggle for a <div> which essentially is a menu with <li>'s etc.

However, whenever it toggles, and I want to click a link it toggles the actual element.

Edit: There was the same selector #userDropdown on both parent elements. Oops 🤔. However, issue remains after removing that.

<div aria-controls="userDropdown" aria-expanded="false" aria-haspopup="true" class=
"topbar-user openPopoverOnClick is-hidden-touch" data-toggle-class="show-popover"
data-toggle-target="#userDropdown" data-toggle-target-only="">
  
<div aria-hidden="true" aria-labelledby="userDropdown" class=
  "popover popover--default popover--m popover--bottom popover--rightAligned transparentScrollbar-Y ps ps--theme_default"
  id="userDropdown" role="listbox">
    <li><a href="/contact">Contact</a></li>
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
  </div>

</div>

Am I missing something in the docs? Here's a GIF for more context.

Screen Recording 2019-05-04 at 06 59 PM

Problem in iOS 9.3.5

The library doesn't work in this OS version (iOS 9.3.5). I thought it was a problem with my site (I'm using the ES5 version), but your examples don't work either.

Is that a problem that should be solved with polyfill.io? What steps should I take to solve this problem?

Thank you very much.

data-toggle-target-parent="" doesnt work with data-toggle-group=""?

I'm trying to setup a menu navigation so each sub nav opens and closes the other however, i also want the parent a tag an active class added as well.
<li><a href="#">Button outer</a><button type="button" class="main-btn" data-toggle-class data-toggle-escape data-toggle-target-next=".sub-menu" data-toggle-group="main-nav" title="Sub Navigation">Button for sub</button></li>

So i set it up like this...

<li><a href="#">Button outer</a><button type="button" class="main-btn" data-toggle-class data-toggle-escape data-toggle-target-next=".sub-menu" data-toggle-group="main-nav" data-toggle-target-parent="a" title="Sub Navigation">Button for sub</button></li>

This works by adding the active class to the a above but now ignores the sub menu group.

Shouldn't these work together?

Programmatic Toggling

Is it possible to trigger a method that toggles an element so I can toggle it via some custom javascript logic?

Some context: I have a table with a button in a tr element that, when clicked, displays "child" tr elements (from the DOM's perspective, though, these tr elements are sibling elements). each of those child tr elements also has a button that displays their own "child" elements. If I toggle the top-level tr button to hide its children, I want to also hide its grandchildren. Does that make sense?

Cancel a toggle event

I need to be able to cancel a toggle event. For instance, I am tracking mouse movement to determine if a user is clicking or dragging on a tab slider. In the event they are dragging. I would like to be able to cancel the toggle in the toggleBefore event hook.

Toggling inputs

Describe the bug
When putting data-toggle-class on a radio input or checkbox input it stops the native functionality of the input (i.e. the radio button does not visibly change). Can this be fixed so that both easy toggle state can occur and normal native input functions also work when interacting with input elements?

There are a few non-native checkbox and radio button demos in the documentation, but I would rather use native elements with the functionality and accessibility benefits and that those have.

e.g:

  <div class="target1 is-active">On</div>
  <div class="target2">Off</div>

  <fieldset>
    <label>
      <input 
        type="radio" 
        name="radios" 
        checked 
        data-toggle-class 
        data-toggle-target="[data-badge='target1']" 
        data-toggle-radio-group="radio" 
        data-toggle-is-active>
      Trigger 1
    </label>
    <label>
      <input 
        type="radio" 
        name="radios" 
        data-toggle-class
        data-toggle-target="[data-badge='target2']"
        data-toggle-radio-group="filter_type">
      Trigger 2
  </label>
  </fieldset>

Expected behavior
To toggle the above active states on the target, and also allow native radio and checkbox inputs to change visibly.

Another plugin similar to this, https://abitgone.github.io/jQuery-Plugins/ClassToggle/ which works in this manor.

Multiple tabs on page within accordion not targeting correctly?

I have two different tab areas on the same page, they are defiantly using two different unique ID's but for some reason two panels cannot be open at the same time even though they are separate.

Is there anything else apart from a unique ID i need to check? The tab navigation itself is also separate to its content in the DOM i/e the tabs navigation is in a sidebar and the tab content is in the main page content.

Data-Toggle-Trigger-Off Not Working With CSS Selectors

Hello! I absolutely love this library, so thanks for your work on it.

I'm having an issue using CSS selectors with data-toggle-trigger-off. I've got a dropdown nav that uses easy toggle state, and then two levels of sub-menus that use it as well. I've made a codepen to show the problem in action: https://codepen.io/awinnett/pen/KKMbBMV?editors=1000

  • Dropdown nav
    • Level one trigger
      • Level two trigger
        • Level three trigger

In this case, I can open the dropdown, use the level one trigger to open the submenu with the level two trigger, and use data-toggle-trigger-off to get back to the menu with the level one trigger. However, if I go down to the level three trigger, I can't go all the way back to level one, because data-toggle-trigger-off stops working at that point at level two after that for some reason.

Thanks in advance for your help!

Adapt easy-toggle-state for ESM projects?

Just wondering if the script could be adapted to use ES module bundling? Would be great to be able to do:

import { easyToggle } from '@easy-toggle-state'

... App functions {}

App.start();

Thanks for your help! :)

Different class on trigger and target?

Let's say I have the below:

<div data-toggle-class="active" data-toggle-target="#target">Trigger</div>
<div id="target">Target</div>

Then active will be added as a class to both the trigger and the target elements.

I can use data-toggle-target-only which disable the class on the target. However, that is not what I want in this case.

I would like one toggle class on the trigger element and another on the target.

Is that possible?

IE 11 emulator edge

I'm getting this console error when trying to test easy toggle in IE11 with emulator Edge set on the compatibility mode.
screen shot 2018-10-15 at 12 56 00 pm
screen shot 2018-10-15 at 12 55 30 pm

Multiple targets with different classes?

I understand that multiple targets can be assigned, but can multiple targets have their own set of classes be toggled as well? Right now it seems the multiple targets must use the same classes.

Remove .git from package

Describe the bug

I use the package as a npm dependency. After installing the package, I noticed I can't update it without manually deleting it. An error occurs:

npm ERR! path /Users/boris/myproject/node_modules/easy-toggle-state
npm ERR! code EISGIT
npm ERR! git /Users/boris/myproject/node_modules/easy-toggle-state: Appears to be a git repo or submodule.
npm ERR! git     /Users/boris/myproject/node_modules/easy-toggle-state
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.

I thinks it's because of the content of the package. There are several folders that should not be there, I think:

drwxr-xr-x   17 boris  staff   544B  6 jui 21:46 .
drwxr-xr-x  917 boris  staff    29K  6 jui 21:46 ..
-rw-r--r--    1 boris  staff   220B 26 oct  1985 .editorconfig
-rw-r--r--    1 boris  staff     0B 26 oct  1985 .eslintignore
-rw-r--r--    1 boris  staff   7,2K 26 oct  1985 .eslintrc.js
drwxr-xr-x    3 boris  staff    96B  6 jui 21:46 .git
drwxr-xr-x    3 boris  staff    96B  6 jui 21:46 .github
-rw-r--r--    1 boris  staff    74B 26 oct  1985 .prettierrc.js
-rw-r--r--    1 boris  staff   1,1K 26 oct  1985 LICENSE
-rw-r--r--    1 boris  staff   3,1K 26 oct  1985 README.md
-rw-r--r--    1 boris  staff   354B 26 oct  1985 TODO.md
drwxr-xr-x    6 boris  staff   192B  6 jui 21:46 dist
drwxr-xr-x    5 boris  staff   160B  6 jui 21:46 docs
-rw-r--r--    1 boris  staff   8,3K 26 oct  1985 logo.png
-rw-r--r--    1 boris  staff   2,6K  6 jui 21:46 package.json
-rw-r--r--    1 boris  staff   2,2K 26 oct  1985 rollup.config.js
drwxr-xr-x    6 boris  staff   192B  6 jui 21:46 src

like the .git folder (provoking the error).

Expected behavior
No more errors.

Desktop (please complete the following information):

  • OS: mac OS Mojave

Additional context
Chocolatine!

cdnjs maybe ?

Is your feature request related to a problem? Please describe.
I think for small site, set up npm, compile it down, and include to the page is quite a bit of work 😅

Describe the solution you'd like
maybe push to cdnjs, so anyone just quickly grasp that and done with that small task (if website ever get big enough to need dedicate fronted team)

A minor thing in the docs

These two lines are equal. In the docs you put window. before the function name. Any reasons why? It is not needed. I removed it in my code and it works fine without it.

window.initEasyToggleState();
initEasyToggleState();

window.initEasyToggleState(); does not work as expected

window.initEasyToggleState(); does not really work.

In my case I have a page with multiple dropdowns. All of them are activated onload. Then I add a new one with ajax.

It's not aware of the new dropdown so I run window.initEasyToggleState();. Now the new dropdown work as expected. However, all the other ones stop working.

I suspected that every old dropdown now has two events on each of them instead of one. It will therefor toggle open and then toggle close in one go.

To prove my theory I added two functions in my ajax.

window.initEasyToggleState();
window.initEasyToggleState();

Now there is a total of 3 events on each old dropdown and 2 on the new dropdown. It means that the new dropdown open and close so fast that it appears to be broken. The old dropdowns now work again. Open + close + open.

I hope you understand what I mean here. In a perfect world it would not duplicate events where they already exists.

Ugly workaround

This workaround will render everything on the screen again which will also remove all events. Very dirty.

document.querySelector('body').outerHTML = document.querySelector('body').outerHTML;

Update

If I already have a dropdown open when doing the above it will not be closed automatically. I solved it with the below code. ($$ is my internal way for document.querySelectorAll).

Basically I remove the toggle class is-open from all elements where it is set. Also data-toggle-state is forced set to false.

$$('falldown-toggle').forEach(el => {
  el.classList.remove('is-open');
});

$$('falldown-content').forEach(el => {
  el.classList.remove('is-open');
  el.dataset.toggleState = false;
});

Help: Toggle Class From Another Element?

Is it possible to toggle a class from another element, for example a slide navigation panel controlled via burger button. Once open close from another div.

Currently i have 2 buttons, the first opens the panel, adding active class, the second appears within that panel to close it, both are below...

Open Panel...
<button type="button" class="site-header__mobile-button lines-nav main-btn " data-toggle-class data-toggle-escape data-toggle-target=" .whole-page, .navigation-panel_holder, .navigation-panel_main, body" title="Navigation">Open Menu</button>

Once open close panel...
<button type="button" class="navigation-panel_main-button main-btn " data-toggle-class data-toggle-escape data-toggle-target=" .whole-page, .navigation-panel_holder, .navigation-panel_main, body" title="Navigation">Close Menu</button>

Both these work fine, but would it be possible to add another class, i'e an overlay outside of the panel so when you click anywhere else it toggles the above?

So a div click toggle class the above, the i try and set this up it seems to do funny things.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.