Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible issue with JS and ViewTransition #8482

Closed
1 task
sparxastronomy opened this issue Sep 10, 2023 · 6 comments · Fixed by #8603
Closed
1 task

Possible issue with JS and ViewTransition #8482

sparxastronomy opened this issue Sep 10, 2023 · 6 comments · Fixed by #8603
Labels
feat: view transitions Related to the View Transitions feature (scope)

Comments

@sparxastronomy
Copy link

Astro Info

Astro                    v3.0.12
Node                     v18.16.0
System                   Windows (x64)
Package Manager          npm
Output                   static
Adapter                  none
Integrations             @astrojs/sitemap
                         @astrojs/tailwind
                         @astrojs/mdx

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

I'm trying out the new ViewTransition update.

I've two basic JS function, one to toggle navbar menu and one to toggle themes.

<script is:inline>
	// Definig the function to attach event to the element
	function attachEvent(selector, event, fn) {
		const matches = document.querySelectorAll(selector);
		if (matches && matches.length) {
			matches.forEach((elem) => {
				elem.addEventListener(event, () => fn(elem), false);
			});
		}
	}

	// Defining the function to check if the menu is open
	const menuCheck = () =>{
		const elem = document.querySelector('[data-aw-toggle-menu]');
		if (elem) {
			elem.classList.remove('expanded');
		}
		document.body.classList.remove('overflow-hidden');
		document.getElementById('header')?.classList.remove('h-screen');
		document.querySelector('#header nav')?.classList.add('hidden');
		return;
	}

	// Defining the function to check and set the theme
	const themeCheck = () =>{
		if (
		localStorage.theme === 'dark' ||
		(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
		) {
			document.documentElement.classList.add('dark');
			} else {
			document.documentElement.classList.remove('dark');
			}
		return;
	}

	// Check theme and menu on window load
	window.addEventListener("DOMContentLoaded", () => themeCheck());
	window.addEventListener("DOMContentLoaded", () => menuCheck());
	// Check theme and menu on after swap
	document.addEventListener("astro:after-swap", () => themeCheck());
	document.addEventListener("astro:after-swap", () => menuCheck());

	window.onload = function () {
		attachEvent('[data-aw-toggle-menu]', 'click', function (elem) {
			elem.classList.toggle('expanded');
			document.body.classList.toggle('overflow-hidden');
			document.getElementById('header')?.classList.toggle('h-screen');
			document.querySelector('#header nav')?.classList.toggle('hidden');


		});
		attachEvent('[data-aw-toggle-theme]', 'click', function () {
			document.documentElement.classList.toggle('dark');
			localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
		});

	};

</script>

The function menuCheck() checks if my navigation menu is open. I've wrapped the entire <nav><nav /> in transition:persist so that on switching between pages, it is behaving as expected and the document.addEventListener("astro:after-swap"...) is rechecking the menu and themes after the content swap.

The nav bar menu is only activated on small devices.

Error:

On using the navbar to go to any of the pages throws a console error:

Uncaught SyntaxError: Identifier 'menuCheck' has already been declared

image

This error is not present for themeCheck. I've also checked that menuCheck is not defined anywhere else in my code.

What's the expected result?

This error shouldn't have appeared, or it should have come for both menuCheck and themeCheck

Link to Minimal Reproducible Example

https://migrate-3--sparxastronomy.netlify.app/

Participation

  • I am willing to submit a pull request for this issue.
@github-actions github-actions bot added the needs triage Issue needs to be triaged label Sep 10, 2023
@Alecyrus
Copy link

identifier 'menuCheck' has already been declared, so you got this error.

CleanShot 2023-09-10 at 21 42 32@2x

@sparxastronomy
Copy link
Author

@Alecyrus I tried the solution in #8466, but it didn't work in my case.
If I execute the script only once by checking with some global flags,

<script is:inline>
  // Use a global flag to track whether the code has been initialized
  let initialized = false;

  // Function to set up your event listeners and perform initial checks
  function initialize() {
    // Check theme and menu
    themeCheck();
    menuCheck();

    // Attach event listeners
    attachEvent('[data-aw-toggle-menu]', 'click', function (elem) {
      elem.classList.toggle('expanded');
      document.body.classList.toggle('overflow-hidden');
      document.getElementById('header')?.classList.toggle('h-screen');
      document.querySelector('#header nav')?.classList.toggle('hidden');
    });

    attachEvent('[data-aw-toggle-theme]', 'click', function () {
      document.documentElement.classList.toggle('dark');
      localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
    });

    // Set the initialized flag to true
    initialized = true;
  }

  // Define the attachEvent function (same as before)

  // Define the menuCheck function (same as before)

  // Define the themeCheck function (same as before)

  // Check theme and menu on window load
  window.addEventListener("DOMContentLoaded", () => {
    if (!initialized) {
      initialize();
    }
  });

  // Check theme and menu on after swap
  document.addEventListener("astro:after-swap", () => {
    if (!initialized) {
      initialize();
    }
  });
</script>

then my dark mode toggle will only work once, which is unexpected.

@matthewp
Copy link
Contributor

@sparxastronomy you want to run your dark mode checks in astro:after-swap. In your example you are not doing so.

@matthewp matthewp added feat: view transitions Related to the View Transitions feature (scope) and removed needs triage Issue needs to be triaged labels Sep 11, 2023
@sparxastronomy
Copy link
Author

@matthewp
The initialize function calls both the dark mode and menuCheck().

Having a global flag to check whether menuCheck has been executed before leaves the navigation menu open after page swap, and also shows the same error.

@matthewp
Copy link
Contributor

@sparxastronomy yes, but you have it so that it only runs once. It needs to run after every page swap (the dark mode stuff does).

@matthewp
Copy link
Contributor

#8603 will fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat: view transitions Related to the View Transitions feature (scope)
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants